Welcome to Questionaries, where you can ask questions and receive answers from other members of the community.

Let us know at info@questionaries.org

MySQL query : all records of one table..

7 like 0 dislike
Hello Guys! I have 2 tables: User and Picture. The Picture table has the key of the user. 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). 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. Any idea? Thanks!
asked 2 years ago by eagle09 (95,490 points)

1 Answer

1 like 0 dislike
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)
answered 2 years ago by marck_don (191,010 points)

Related questions

8 like 0 dislike
1 answer
8 like 0 dislike
0 answers
asked 2 years ago by eagle09 (95,490 points)
8 like 0 dislike
1 answer
asked 2 years ago by eagle09 (95,490 points)
9 like 0 dislike
0 answers
7 like 0 dislike
0 answers
asked 2 years ago by eagle09 (95,490 points)