gpt4 book ai didi

MySQL 查询 : all records of one table plus count of another table

转载 作者:可可西里 更新时间:2023-11-01 07:49:21 24 4
gpt4 key购买 nike

我有 2 个表:用户和图片。 Picture 表具有用户的键。所以基本上每个用户可以有多张图片,每张图片属于一个用户。现在,我正在尝试进行以下查询:我想选择所有用户信息加上他拥有的图片总数(即使它是 0)。我怎样才能做到这一点?可能这听起来很简单,但我一直在尝试,但似乎找不到正确的查询。我唯一可以选择的是此信息,但仅适用于至少拥有 1 张图片的用户,这意味着图片表至少有该键的一条记录......但我也想考虑没有任何图片的用户.任何想法?谢谢!

最佳答案

您可能想尝试以下方法:

SELECT    u.name,
IFNULL(sub_p.total, 0) num
FROM users u
LEFT JOIN ( SELECT COUNT(*) total, user_id
FROM pictures
GROUP BY user_id
) sub_p ON (sub_p.user_id = u.user_id);

测试用例:

CREATE TABLE users (user_id int, name varchar(10));
CREATE TABLE pictures (user_id int);

INSERT INTO users VALUES (1, 'Joe');
INSERT INTO users VALUES (2, 'Peter');
INSERT INTO users VALUES (3, 'Bill');

INSERT INTO pictures VALUES (1);
INSERT INTO pictures VALUES (1);
INSERT INTO pictures VALUES (2);
INSERT INTO pictures VALUES (2);
INSERT INTO pictures VALUES (2);

结果:

+-------+-----+
| name | num |
+-------+-----+
| Joe | 2 |
| Peter | 3 |
| Bill | 0 |
+-------+-----+
3 rows in set (0.00 sec)

关于MySQL 查询 : all records of one table plus count of another table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2839738/

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