gpt4 book ai didi

mysql - 自连接查询以获取一张表中的结果

转载 作者:行者123 更新时间:2023-11-30 00:25:49 25 4
gpt4 key购买 nike

我有一个如下所示的表格。

+------+----------+--------+
| id |sender_id |receiver_id|
+------+----------+--------+
| 1 | 1 | 4 |
| 2 | 1 | 34 |
| 3 | 4 | 1 |
| 4 | 11 | 8 |
| 5 | 24 | 4 |
| 6 | 11 | 5 |
+------+----------+--------+

我想看到如下所示的结果。

+------+----------+--------+
|user_id|sent |receive |
+------+----------+--------+
| 1 | 2 | 1 |
| 4 | 1 | 2 |
| 5 | 0 | 1 |
| 8 | 0 | 1 |
| 11 | 2 | 0 |
| 24 | 1 | 0 |
| 34 | 0 | 1 |
+------+----------+--------+

我想在一张表中显示我的结果,其中一列 user_id(所有唯一的 sender_id 和receiver_id)作为 user_id,发送(count(sender_id)作为发送,count(receiver_id))作为接收。这样我就可以在一张表中获得每个用户发送和接收消息编号的结果。我正在尝试自连接查询,但没有得到我预期的结果。

最佳答案

我会使用这个查询:

SELECT user_id, SUM(sent), SUM(receive)
FROM (
SELECT sender_id AS user_id, COUNT(*) AS sent, 0 AS receive
FROM tablename
GROUP BY sender_id
UNION ALL
SELECT receiver_id AS user_id, 0 AS sent, COUNT(*) AS receive
FROM tablename
GROUP BY receiver_id
) s
GROUP BY user_id

请参阅 fiddle here .

关于mysql - 自连接查询以获取一张表中的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22896974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com