简体   繁体   English

MySQL查询:一个表的所有记录加上另一个表的计数

[英]MySQL query : all records of one table plus count of another table

I have 2 tables: User and Picture. 我有2个表:用户和图片。 The Picture table has the key of the user. Picture表具有用户的密钥。 So basically each user can have multiple pictures, and each picture belongs to one user. 所以基本上每个用户可以有多个图片,每个图片属于一个用户。 Now, I am trying to make the following query: I want to select all the user info plus the total number of pictures that he has (even if it's 0). 现在,我正在尝试进行以下查询:我想选择所有用户信息加上他拥有的图片总数(即使它是0)。 How can I do that? 我怎样才能做到这一点? Probably it sounds quite simple, but I am trying and trying and can't seem to find the right query. 可能听起来很简单,但我正在努力尝试,似乎无法找到正确的查询。 The only thing I could select is this info, but only for users that have at least 1 picture, meaning that the Pictures table has at least one record for that key... But I also wanna consider the users that don't have any. 我唯一可以选择的是这个信息,但仅适用于至少有1张图片的用户,这意味着图片表至少有一张该密钥的记录...但我也想考虑没有任何记录的用户。 Any idea? 任何想法? Thanks! 谢谢!

You may want to try the following: 您可能想尝试以下方法:

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);

Test case: 测试用例:

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);

Result: 结果:

+-------+-----+
| name  | num |
+-------+-----+
| Joe   |   2 |
| Peter |   3 |
| Bill  |   0 |
+-------+-----+
3 rows in set (0.00 sec)
SELECT u.name, COUNT(p.picture) AS number
FROM User u
LEFT JOIN Picture p
  ON u.id = p.userid
GROUP BY p.userid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM