1
4

3 回答 3

9

You should be able to JOIN the tables on the profile.id and the profileid in the other tables.

If you are sure the profileid exists in all three tables, then you can use an INNER JOIN. The INNER JOIN returns matching rows in all of the tables:

select p.id,
  p.name,
  c.desc ContactDesc,
  a.desc AddressDesc
from profile p
inner join contact c
  on p.id = c.profileid
inner join address a
  on p.id = a.profileid
where p.name = 'bla'
  and c.ord = 1
  and a.ord = 1

If you are not sure that you will have matching rows, then you can use a LEFT JOIN:

select p.id,
  p.name,
  c.desc ContactDesc,
  a.desc AddressDesc
from profile p
left join contact c
  on p.id = c.profileid
  and c.ord = 1
left join address a
  on p.id = a.profileid
  and a.ord = 1
where p.name = 'bla'

If you need help learning JOIN syntax, here is a great visual explanation of joins

于 2013-03-01T15:22:59.927 回答
1

This query below only selects column when an ID from Profile table has atleast one match on tables: Contact and Address. If one or both of them are nullable, use LEFT JOIN instead of INNER JOIN because LEFT JOIN displays all records from the Left-hand side table regardless if it has a match on other tables or not.

SELECT  a.*, 
        b.desc as BDESC,
        c.desc as CDESC
FROM    Profile a
        INNER JOIN Contact b
            ON a.ID = b.ProfileID
        INNER JOIN Address c
            ON a.ID = c.ProfileID
WHERE   b.ORD = 1 AND
        c.ORD = 1 AND
        a.Name = 'nameHERE'

The LEFT JOIN version:

SELECT  a.*, 
        b.desc as BDESC,
        c.desc as CDESC
FROM    Profile a
        INNER JOIN Contact b
            ON a.ID = b.ProfileID AND b.ORD = 1
        INNER JOIN Address c
            ON a.ID = c.ProfileID AND c.ORD = 1
WHERE   a.Name = 'nameHERE'

To further gain more knowledge about joins, kindly visit the link below:

于 2013-03-01T15:23:48.807 回答
0

i have created working demo as your requirement :

The query bellow will retrieve all matching records from the database.its retrieving profile id,name stufff and description of contact tables

select p.id,p.name,p.stauff,c.descr,a.descr from profile as p
 inner join contact as c on c.profileid=p.id
 inner join address as a on a.profileid=p.id
 where p.name="bla" and c.ord=1 and a.ord=1
于 2013-03-01T19:12:48.513 回答