日期:2014-05-18  浏览次数:20540 次

关于三张表的联合查找 求指教
a表
 
id name 

b表

id name data

c表

id name data

怎么根据用a表 查找出b, c中的data

------解决方案--------------------
select b.data,c.data from a 
join b on a.name=b.name
join c on a.name=c.name
------解决方案--------------------
--如果只根据ID查,则如下:
select a.* , b.* , c.* from a 
left join b on a.id = b.id
left join c on a.id = c.id

--如果根据ID+name查,则如下:
select a.* , b.* , c.* from a 
left join b on a.id = b.id and a.name = b.name
left join c on a.id = c.id and a.name = c.name

------解决方案--------------------
SQL code

SELECT *FROM 
(
SELECT B.DATA FROM B
UNION ALL
SELECT C.DATA FROM C
)AS NEW_TAB
WHERE NAME IN
(
SELECT NAME FROM A
)
--或者
WHERE ID IN
(
SELECT ID FROM A
)

------解决方案--------------------
SQL code

SELECT *FROM 
( 
SELECT DISTINCT ID,NAME,DATA FROM B 
UNION ALL
SELECT DISTINCT ID,NAME,DATA FROM C 
)AS NEW_TAB
WHERE NAME IN 
( 
SELECT NAME FROM A
) 
--或者 
WHERE ID IN 
( 
SELECT ID FROM A
 )