如何从多个表中只获取特定记录?

时间:2014-12-11 11:23:35

标签: mysql sql database query-optimization

我有表' table1 ',' table2 ',' table3 '和' table4 '。 'table1'有一个列'account',基于我需要从'table2'或'table3'或'table4'获取关于另一列'user_id'的记录。

我正在使用像

这样的查询
SELECT * 
FROM table1 
LEFT OUTER JOIN table2 ON table1.user_id = table2.user_id
LEFT OUTER JOIN table2 ON table1.user_id = table2.user_id
LEFT OUTER JOIN table3 ON table1.user_id = table3.user_id

使用这个我得到很多NULL值因为table1的每个记录只有'table2'或'table3'或'table4'中的记录。

现在的输出就像 -

t1.user_id  | t1.post_id     | t2.token   | t3.token  | t4.token
 1          |      1         |   xyz      |   NULL    | NULL      
 1          |      1         |   NULL     |   abc     | NULL  
 1          |      1         |   NULL     |   NULL    | etc  

需要就像

 t1.user_id | t1.post_id     | token 
 1          |      1         |   xyz       
 1          |      1         |   abc  
 1          |      1         |   etc

t2,t3和t4可以有多于1列来选择。

4 个答案:

答案 0 :(得分:1)

使用COALESCE()函数会更简单:

SELECT 
    t1.user_id, 
    t1.post_id, 
    COALESCE(t2.Token, t3.Token, t4.Token) AS Token
FROM table1 
LEFT OUTER JOIN table2 ON table1.user_id = table2.user_id
LEFT OUTER JOIN table2 ON table1.user_id = table2.user_id
LEFT OUTER JOIN table3 ON table1.user_id = table3.user_id

答案 1 :(得分:1)

为此,您可以使用 COALESCE()函数。

COALESCE()函数返回列表中的第一个非空值。 例如

select COALESCE(NULL, NULL, NULL, 'abc', NULL, 'xyz');

上述查询的结果为 abc

更新的查询:

SELECT 
t1.user_id, 
t1.post_id, 
COALESCE(t2.Token, t3.Token, t4.Token) AS token 
FROM table1 
LEFT OUTER JOIN table2 ON table1.user_id = table2.user_id
LEFT OUTER JOIN table2 ON table1.user_id = table2.user_id
LEFT OUTER JOIN table3 ON table1.user_id = table3.user_id

答案 2 :(得分:0)

SELECT * 
FROM table1 t1
INNER JOIN table2 t2 ON t1.user_id = t2.user_id
INNER JOIN table3 t3 ON t1.user_id = t3.user_id
INNER JOIN table4 t4 ON t1.user_id = t4.user_id

答案 3 :(得分:0)

你可以这样做:

SELECT 
  t1.user_id,
  t1.post_id,
  MAX(t2.token) AS token2, 
  MAX(t3.token) AS token3, 
  MAX(t4.token) AS token4
FROM table1 AS t1
LEFT OUTER JOIN table2 AS t2 ON t1.user_id = t2.user_id
LEFT OUTER JOIN table3 AS t3 ON t1.user_id = t3.user_id
LEFT OUTER JOIN table4 AS t4 ON t1.user_id = t4.user_id
GROUP BY t1.user_id, t1.post_id