SQL - 使用JOIN“合并”3个表

时间:2013-07-22 13:06:50

标签: mysql sql join

我想根据两个关系表

从表中选择用户

结构:

[user]

uid | firstname | lastname | ...
---------------------------------
482 | USERa     | USERa    | ...
885 | USERb     | USERb    | ...
405 | USERc     | USERc    | ...
385 | USERd     | USERd    | ...

[news_info]

uid_local   | uid_foreign
--------------------------------
125         | 482       
100         | 405       

[news_add]

uid_local   | uid_foreign
--------------------------------
125         | 885   
105         | 385   

现在我想通过uid_local选择USERa和USERb - > 125,来自[news_info]和[news_add]

SELECT 
  nnfo.uid_local, 
  user.* 
FROM user
  JOIN news_info nnfo
    ON nnfo.uid_foreign = user.uid
WHERE nnfo.uid_local = 125 

result = USERa //工作

SELECT 
  nadd.uid_local,
  user.* 
FROM user
  JOIN news_add nadd
    ON nadd.uid_foreign = user.uid
WHERE nadd.uid_local = 125

result = USERb //工作

现在将sql语句“合并”为一个...以获取USERa和USERb

SELECT 
  nnfo.uid_local, 
  nadd.uid_local,
  user.* 
FROM user
  JOIN news_info nnfo
    ON nnfo.uid_foreign = user.uid
  JOIN news_add nadd
    ON nadd.uid_foreign = user.uid
WHERE nnfo.uid_local = 125 AND nadd.uid_local = 125

结果=空//没有错误.....

出了什么问题......我尝试了其他一些陈述但没有结果:(

2 个答案:

答案 0 :(得分:2)

您的uid_local ID存在于不同的行上:因此,当您想要AND结果时,您什么也得不到(因为没有任何内容相交)。你可以用联盟做到这一点:

SELECT * from
(
SELECT 
  nnfo.uid_local, 
  user.firstname, user.lastname 
FROM user
  JOIN news_info nnfo
    ON nnfo.uid_foreign = user.uid
WHERE nnfo.uid_local = 125 

UNION ALL

SELECT 
  nadd.uid_local,
  user.firstname, user.lastname 
FROM user
  JOIN news_add nadd
    ON nadd.uid_foreign = user.uid
WHERE nadd.uid_local = 125
) x

答案 1 :(得分:1)

合并查询结果时,有两种不同的方法:

  • UNION
  • 的JOIN

要知道选择哪一个,您必须知道要合并的2个查询中的表之间是否存在技术链接。在您的情况下,有一个功能链接(nnfo.uid_local = 125 AND nadd.uid_local = 125),但加入这两个Universe是不够的。你仍然可以只用一个SELECT来获得结果,但我认为最终的结果将不清楚,并且在某种程度上并不真正符合SQL提供的精神。

我会去UNION解决方案:

SELECT 
  nnfo.uid_local, 
  user.* 
FROM user
  JOIN news_info nnfo
    ON nnfo.uid_foreign = user.uid
WHERE nnfo.uid_local = 125 
UNION
SELECT 
  nadd.uid_local,
  user.* 
FROM user
  JOIN news_add nadd
    ON nadd.uid_foreign = user.uid
WHERE nadd.uid_local = 125

编辑:我看到davek的结果实现了UNION ALL而不是UNION。我假设您希望只返回USERa一次,如果它恰好出现在两个独立的查询中,这就是为什么我使用简单的UNION运算符和UNION ALL也会返回重复结果的原因。