简体   繁体   中英

COUNT and SELECT query from two tables

I have these two tables:

1. users
   -id
   -name
   -email
   -rank

2. pages
   -user
   -id

I need to select all the data from users and count how many pages did he wrote (from pages user is the id of the user from users table).

Can you make it into 1 complex query?

select u.*,count(p.*) from users u left join pages p on u.id=p.user group by u.id;

I can't make it into a complex query, but here's a simple one:

SELECT u.name, u.email, u.rank, u.id, count(p.id) as 'PageCount'
FROM Users u
JOIN Pages p ON
    p.id = u.id
GROUP BY u.name, u.email, u.rank, u.id

Yes, do it like this:

select u.id, u.name, u.email, u.rank, count(p.id) as 'counter' from users u
inner join pages p on p.user = u.id
group by u.id, u.name, u.email, u.rank

You group by the users info and calculate (count) the number of pages for each user.

How about this.

select   u.id, count(p.id) as 'number_of_pages_wrote'
from     users u inner join pages p
on       u.id = p.id
group by u.id;
select   users.id, users.name,users.email,users.rank, count(pages.id) 
from     users,pages 
where    users.id = pages.user 
group by users.id

You can do it like this -

SELECT u.*, p.count
FROM users u,
     (SELECT pa.id, count(1) FROM pages pa WHERE pa.id = u.id) p
WHERE u.id = p.id 

那么这个简单的查询呢

 SELECT user, COUNT(*) AS pages FROM page GROUP BY user 

This can be accomplished by a JOIN .

For instance,

SELECT * FROM pages 
INNER JOIN users ON (users.id=pages.user) 
WHERE users.id=5

will select all pages from userid 5. I'll let you do the rest to include the aggregate function ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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