SQL选择多个表

时间:2017-03-07 14:55:45

标签: mysql sql

我对SQL有疑问。

我有3张表格,消息,付款和报告。

我想从一个查询中的每个表中获取用户的所有事件,所以这是我想要获得的:

SELECT * FROM messages WHERE receiver_id = 10
SELECT * FROM payments WHERE client_id = 10
SELECT * FROM reports WHERE receiver_id = 10

但是在1个查询中。

这可能吗?

Table structures:
- messages
id
sender_id
receiver_id
type
text
created_at
updates_at

- payments
id
user_id
client_id
method
cost
status
text
created_at
updated_at

- reports
id
sender_id
receiver_id
text
created_at
updates_at

4 个答案:

答案 0 :(得分:0)

它非常直接,提供的receiver_id和client_id保持相同的值:

SELECT * FROM `messages` LEFT JOIN `payments` ON 
`messages`.`receiver_id` = `payments`.`client_id` LEFT JOIN `reports`
ON `messages`.`receiver_id` = `reports`.`receiver_id`

答案 1 :(得分:0)

我真的不明白你想要什么,你想在1个查询中获取所有数据,还是需要加入它们?

如果您想要一张表中的所有数据,我可以这样做,我想:

SELECT * FROM messages as M, payments as P, reports as R
WHERE M.receiver_id, P.client_id, R.receiver_id = 10

否则,您需要向我们展示关于这种关系的更多细节

答案 2 :(得分:0)

如果3个表之间没有关系,那么您可以使用UNION。它可以这么简单:

SELECT receiver_id as event_id, event_name, event_description, event_timestamp FROM messages WHERE receiver_id = 10
UNION
SELECT client_id as event_id, event_name, event_description, event_timestamp FROM payments WHERE client_id = 10
UNION
SELECT receiver_id as event_id, event_name, event_description, event_timestamp FROM reports WHERE receiver_id = 10

这假设您感兴趣的所有表中都有一组通用的列。但是,如果列具有不同的名称但包含相同的数据(和数据类型),则可以使用AS重命名查询中的列实现UNION

SELECT receiver_id as event_id, col1 as event_name, col2 as event_description, col3 event_timestamp FROM messages WHERE receiver_id = 10
UNION
SELECT client_id as event_id, col_a as event_name, col_b as event_description, col_c event_timestamp FROM payments WHERE client_id = 10
UNION
SELECT receiver_id as event_id, col_x as event_name, col_y as event_description, col_z event_timestamp FROM reports WHERE receiver_id = 10

请注意,UNION将消除数据集中的重复行。如果这不是您想要的行为,则使用UNION ALL代替(它不会消除重复)。

另请注意,如果表中的列数据类型不同,则必须将它们转换为通用类型。转换高度依赖于您的DBMS,因此请确保使用正确的方法来执行此操作。

答案 3 :(得分:0)

您可以使用Union或Union All来连接3个查询的结果集。但是,所有3个表必须具有相同数量的列才能工作。发布表结构以获得更精确的解决方案。

SELECT * FROM messages WHERE receiver_id = 10
Union All
SELECT * FROM payments WHERE client_id = 10
Union All
SELECT * FROM reports WHERE receiver_id = 10