Jump to content

Counting data from 2 tables


JohnL

Recommended Posts

I have two tables: USERS and PICTURES

Sample data for USERS:
[table]
[tr][td]id[/td][td]birth_date[/td][/tr]
[tr][td]1[/td][td]1970-01-01[/td][/tr]
[tr][td]2[/td][td]1987-01-01[/td][/tr]
[tr][td]3[/td][td]1980-01-01[/td][/tr]
[tr][td]4[/td][td]1981-01-25[/td][/tr]
[tr][td]5[/td][td]1982-07-01[/td][/tr]
[tr][td]6[/td][td]1985-01-25[/td][/tr]
[tr][td]7[/td][td]1978-07-01[/td][/tr]
[tr][td]8[/td][td]1970-01-01[/td][/tr]
[/table]

Sample data for PICTURES
[table]
[tr][td]id[/td][td]pictureNo[/td][/tr]
[tr][td]1[/td][td]1[/td][/tr]
[tr][td]1[/td][td]2[/td][/tr]
[tr][td]1[/td][td]3[/td][/tr]
[tr][td]7[/td][td]1[/td][/tr]
[tr][td]7[/td][td]2[/td][/tr]
[/table]

The following query
SELECT floor(period_diff(extract(year_month from NOW()),extract(year_month from birth_date))/12) as age, count(*) FROM db.USERS u group by age order by age;

Would return
[table]
[tr][td]age[/td][td]count(*)[/td][/tr]
[tr][td]20[/td][td]1[/td][/tr]
[tr][td]22[/td][td]1[/td][/tr]
[tr][td]24[/td][td]1[/td][/tr]
[tr][td]26[/td][td]1[/td][/tr]
[tr][td]27[/td][td]1[/td][/tr]
[tr][td]28[/td][td]1[/td][/tr]
[tr][td]37[/td][td]2[/td][/tr]
[/table]

This is half my Job done. I do not know how to go about doing the next task which is to count how many users has uploaded at least one picture within that age group.

What query is required to return a result looking something like
[table]
[tr][td]age[/td][td]age count(*)[/td][td]pictures count(*)[/td][/tr]
[tr][td]20[/td][td]1[/td][td]0[/td][/tr]
[tr][td]22[/td][td]1[/td][td]0[/td][/tr]
[tr][td]24[/td][td]1[/td][td]0[/td][/tr]
[tr][td]26[/td][td]1[/td][td]0[/td][/tr]
[tr][td]27[/td][td]1[/td][td]1[/td][/tr]
[tr][td]28[/td][td]1[/td][td]0[/td][/tr]
[tr][td]37[/td][td]2[/td][td]1[/td][/tr]
[/table]
Link to comment
https://forums.phpfreaks.com/topic/33034-counting-data-from-2-tables/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.