简体   繁体   中英

mysql - select from 2 tables, count and group by column

So I have 2 tables:

pages:

id    page    visit_id
1      6         65
2      7         65
3      2         66
4      10        67

visits:

id    flipbook    
65      april         
66      april         
67      may   

I want to return how many pages were viewed for each flipbook:

april: 3 
may: 1

My query looks like this:

"SELECT a.flipbook, (SELECT count(b.page) from pages b WHERE a.id = b.visit_id) AS total FROM visits a GROUP BY a.flipbook"

But it returns:

april: 1 
may: 1

Because it gets only the last visit from april, where we visited one page.

Any thoughts?

select a.flipbook, count(*)
  from visits a 
    inner join pages p
      on a.id = p.visit_id
  group by a.flipbook

There are no need for subqueries - this is just a basic join and aggregate.

try to use query like this

SELECT a.flipbook,COUNT(*) AS total
FROM visits a 
LEFT JOIN pages b ON a.id = b.visit_id
GROUP BY a.flipbook

Um, bit off track there...

SELECT v.flipbook
     , COUNT(*) pages_viewed 
  FROM visits v 
  JOIN pages p 
    ON visit_id = v.id 
 GROUP 
    BY v.flipbook;

Use an OUTER JOIN and count something else if you want '0' results too.

you can try use query like this :

SELECT v.flipbook, COUNT(*) AS total
FROM pages p 
LEFT JOIN visits v ON p.visit_id=v.id 
GROUP BY v.flipbook

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