![]() |
|
|
|||||||
![]() |
|
|
Thread Tools | Rate Thread |
|
|
PM User | #1 |
|
New Coder ![]() Join Date: Sep 2009
Posts: 16
Thanks: 1
Thanked 0 Times in 0 Posts
![]() |
Need data from 2 columns in 1 query
Edit: Should say 2 tables in 1 query
I need to select: select * from blogs; and I need to pair this with select count(*) from comments group by aid; where aid is in both blogs as the main key, and aid is just a regular field in the comments table Last edited by MattNolan; 11-04-2009 at 07:44 PM.. |
|
|
|
|
|
PM User | #2 |
|
Master Coder ![]() Join Date: Dec 2005
Location: Utah, USA, Northwestern hemisphere, Earth, Solar System, Milky Way Galaxy, Alpha Quadrant
Posts: 5,411
Thanks: 32
Thanked 373 Times in 364 Posts
![]() ![]() ![]() ![]() ![]() |
The way to do this is to take the simple COUNT(*) query, grouping by the id:
Code:
SELECT COUNT(*), table_id FROM table2 GROUP BY by table_id Code:
SELECT * FROM main_table as m
JOIN (
SELECT COUNT(*), main_table_id
FROM table2
GROUP BY main_table_id) as count_table
ON m.table_id = count_table.main_id
__________________
|
|
|
|
|
|
PM User | #3 |
|
Senior Coder ![]() Join Date: Feb 2009
Location: Snohomish, WA
Posts: 4,061
Thanks: 18
Thanked 660 Times in 652 Posts
![]() ![]() |
Why the inner SELECT???
Why not a simple JOIN?? Code:
SELECT B.field1, B.field2, B.field3, COUNT(c.aid) AS howManyComments FROM blogs AS B INNER JOIN comments AS C ON B.aid = C.aid GROUP BY B.field1, B.field2, B.field3 If you want all blogs records to appear, even if the count of comments is zero, then just change the INNER JOIN to a LEFT JOIN.
__________________
"Old age and cunning win out over youth and enthusiasm every time." |
|
|
|
|
|
PM User | #5 | |
|
Senior Coder ![]() Join Date: Feb 2009
Location: Snohomish, WA
Posts: 4,061
Thanks: 18
Thanked 660 Times in 652 Posts
![]() ![]() |
Quote:
But you make a point worth considering, for sure. My gut feel is that you won't see a performance difference between the two, but maybe I'm wrong. Will have to test that out one of these days.
__________________
"Old age and cunning win out over youth and enthusiasm every time." |
|
|
|
|
![]() |
| Bookmarks |
| Thread Tools | |
| Rate This Thread | |
|
|