NYCPHP Meetup

NYPHP.org

[nycphp-talk] MySQL: count()children on 2 related tables in 1 query

SyAD at aol.com SyAD at aol.com
Wed Jan 5 10:37:03 EST 2011


 
Is this possible in MySQL?:
 
SELECT 
    parent.id, 
    parent.someColumn, 
    (SELECT count(*) FROM child_table_1 as c1 WHERE c1.parent_id = 
parent.id) as cnt1,
    (SELECT count(*) FROM child_table_2 as c2 WHERE c2.parent_id = 
parent.id) as cnt2
FROM parent
 
Not sure if this would give you the data you want -- I tend to use this 
form instead of JOINs with A => B and A => C, but I mostly am using MS SQL 
Server.
 
Steve

In a message dated 1/4/2011 4:28:45 PM Eastern Standard Time, 
rmarscher at beaffinitive.com writes:



On Jan 4, 2011, at 4:02 PM, Dan Cech wrote:


Sorry, forgot the ON clauses:

SELECT parent.id, parent.someColumn, c1.cnt, c2.cnt
FROM parent
LEFT JOIN (
SELECT child_table_1.parent_id,count(child_table_1.id) as cnt
FROM child_table_1
GROUP BY child_table_1.parent_id
) AS c1 ON c1.parent_id=parent.id
LEFT JOIN (
SELECT child_table_2.parent_id,count(child_table_2.id) as cnt
FROM child_table_2
GROUP BY child_table_2.parent_id
) AS c2 ON c2.parent_id=parent.id





-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.nyphp.org/pipermail/talk/attachments/20110105/828a7780/attachment.html>


More information about the talk mailing list