我有3个表,它们有一个公共字段user_id
gain_table
+--------------------------+
|user_id | gain_count |
| 1 | 3 |
| 2 | 4 |
| 3 | 1 |
+--------------------------+
consum_table
+--------------------------+
|user_id |consume_count |
| 2 | 5 |
| 5 | 4 |
| 6 | 7 |
+--------------------------+
join_table
+--------------------------+
|user_id | join_count |
| 1 | 3 |
| 2 | 1 |
| 5 | 4 |
+--------------------------+
我想要这样的输出:
输出:
+-----------+--------------+--------------+------------+
|user_id | gain_count |consume_count | join_count |
| 1 | 3 | 0 | 3 |
| 2 | 4 | 5 | 1 |
| 3 | 1 | 0 | 0 |
| 5 | 0 | 4 | 4 |
| 6 | 0 | 7 | 0 |
+-----------+--------------+--------------+------------+
是的,我希望将这三个表合并为一个表,如果某些字段值为空,则将该字段值赋予0。
如何编写MySQL查询?
答案 0 :(得分:3)
您可以使用所有表中的UNION
来获得所需的结果,为每个表中不存在的值选择0,然后按user_id
对所有字段求和:
SELECT user_id, SUM(gain_count) AS gain_count,
SUM(consume_count) AS consume_count, SUM(join_count) AS join_count
FROM (SELECT user_id, gain_count, 0 AS consume_count, 0 AS join_count FROM gain_table
UNION ALL
SELECT user_id, 0, consume_count, 0 FROM consume_table
UNION ALL
SELECT user_id, 0, 0, join_count FROM join_table) u
GROUP BY user_id
输出:
user_id gain_count consume_count join_count
1 3 0 3
2 4 5 1
3 1 0 0
5 0 4 4
6 0 7 0
答案 1 :(得分:0)
以下是使用ansi标准sql的方法:
SELECT coalesce(g.user_id, c.user_id, j.user_id) user_id
, coalesce(g.gain_count, 0) gain_count
, coalesce(c.consume_count, 0) consume_count
, coalesce(j.join_count,0) join_count
FROM gain_table g
FULL JOIN consume_table c on c.user_id = g.user_id
FULL JOIN join_table j on j.user_id = coalsece(c.user_id, g.user_id)
自92版本以来,这已成为ansi标准的一部分,除MySql以外的每个主要数据库都可以做到。 MySql必须这样做:
SELECT ids.user_id
, coalesce(g.gain_count, 0) gain_count
, coalesce(c.consume_count, 0) consume_count
, coalesce(j.join_count, 0) join_count
FROM (
SELECT user_id FROM gain_table
UNION
SELECT user_id FROM consume_table
UNION
SELECT user_id FROM join_table
) ids
LEFT JOIN gain_table g on g.user_id = ids.user_id
LEFT JOIN consume_table c on c.user_id = ids.user_id
LEFT JOIN join_table j on j.user_id = ids.user_id