如何在SQL中联接多个表

时间:2018-12-15 14:22:00

标签: sql postgresql inner-join

嗨,朋友,我有3张表充值,撤回并转移这3张表属于用户表。我必须找到属于用户的所有记录。我尝试使用内部联接,如下所示:-

SELECT * FROM users u
INNER JOIN topups t
  ON u.id = t.user_id
INNER JOIN withdraws w
  ON u.id = w.user_id
INNER JOIN transfers tf
  ON u.id = tf.user_id

但是此查询仅返回3个表之间的公共记录。我必须为每个表查找属于用户的所有那些记录。

假设我在topups中有2条记录属于用户ID 1,在提款中有3条记录属于用户ID 2,在转移中有5条记录属于用户ID 3,所以我应该获得总计10条记录。

样本数据:-

充值

+--------+---------+---------+
| amount | result  | user_id |
+--------+---------+---------+
|     10 | success |       1 |
|     20 | failed  |       2 |
+--------+---------+---------+

提现

+---------+----------+
|w_amount |  user_id |
+---------+----------+
|     10  |        1 |
|     20  |        2 |
|     30  |       10 |
+---------+----------+

转移

+--------+--------+---------+
| method | amount | user_id |
+--------+--------+---------+
| abc    |     10 |       3 |
| xyz    |     20 |       4 |
+--------+--------+---------+

用户

+----+---------+--------+
| id |  f_name | l_name |
+----+---------+--------+
|  1 |    abc  |    xyz |
|  2 |    abc  |    xyz |
|  3 |    abc  |    xyz |
|  4 |    abc  |    xyz |
|  5 |    abc  |    xyz |
|  6 |    abc  |    xyz |
+----+---------+--------+

预期产量

+--------+---------+---------+----------+---------+
| amount | result  | user_id | w_amount |  method |
+--------+---------+---------+----------+---------+
|     10 | success |       1 |          |         |
|     20 | failed  |       2 |          |         |
|        |         |       1 |       10 |         |
|        |         |       2 |       20 |         |
|        |         |       3 |          | abc     |
|        |         |       4 |          | xyz     |
+--------+---------+---------+----------+---------+

请帮助,谢谢。

2 个答案:

答案 0 :(得分:1)

将他们与用户和号码保持联系即可。

SELECT 
 tup.amount, tup.result, 
 usr.id as user_id, 
 wd.w_amount, 
 trans.method
FROM users usr
CROSS JOIN (SELECT generate_series n FROM generate_series(1, 3)) AS nr
LEFT JOIN topups tup ON tup.user_id = usr.id AND nr.n = 1
LEFT JOIN withdraws wd ON wd.user_id = usr.id AND nr.n = 2
LEFT JOIN transfers trans ON trans.user_id = usr.id AND nr.n = 3
WHERE (tup.user_id IS NOT NULL OR wd.user_id IS NOT NULL OR trans.user_id IS NOT NULL)
ORDER BY tup.user_id, wd.user_id, trans.user_id

测试here

其他:

基于评论here

的变体

答案 1 :(得分:0)

您可以使用left join来代替inner join

SELECT * FROM users u
LEFT JOIN topups t
  ON u.id = t.user_id
LEFT JOIN withdraws w
  ON u.id = w.user_id
LEFT JOIN transfers tf
  ON u.id = tf.user_id