[英]How to get only specific record from multiple tables?
I have tables ' table1 ', ' table2 ',' table3 ' and ' table4 ' .我有表 ' table1 '、' table2 '、' table3 ' 和 ' table4 '。 'table1' has a column 'account' on basis of I need to get record from 'table2' or 'table3' or 'table4' with respect of another column 'user_id'.
“table1”有一个“account”列,因为我需要从“table2”或“table3”或“table4”中获取关于另一列“user_id”的记录。
I am using query like我正在使用查询
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
using this I am getting lots of NULL values because each record of table1 will have only record in either 'table2' or 'table3' or 'table4'.使用这个我得到了很多 NULL 值,因为 table1 的每条记录都只会在 'table2' 或 'table3' 或 'table4' 中有记录。
Present output is like -目前的输出就像 -
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
needed is like需要就像
t1.user_id | t1.post_id | token
1 | 1 | xyz
1 | 1 | abc
1 | 1 | etc
t2,t3 and t4 can have more than 1 column to select. t2、t3 和 t4 可以有 1 个以上的列可供选择。
It would be much simpler to use the COALESCE()
function:使用
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
For this you can use COALESCE() function.为此,您可以使用COALESCE()函数。
The COALESCE() function returns the first non-null value in a list. COALESCE() 函数返回列表中的第一个非空值。 for eg
例如
select COALESCE(NULL, NULL, NULL, 'abc', NULL, 'xyz');
the result of the above query is abc .上述查询的结果是abc 。
Updated query :更新查询:
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
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
You can do this:你可以这样做:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.