Jump to content

Recommended Posts

If I have these three tables:

 

Table 1

t1ID  [other fields]

 

Table 2

t2ID  t1ID  [other fields]

 

Table 3

t3ID  t1ID  [other fields]

 

If I am only paying attention to, let's say, t1ID = 2 (from Table 1), is there a way to get a count of how many entries in Table 2 and Table 3 have a t1ID = 2 and still return 0 in that case? I want to make sure I still get results in the case that one or both have 0 entries that match. The only way I have been able to do this is with subqueries, but it seems really inefficient to do so (especially when I have to do it for multiple tables).

 

Thanks for any help.

Link to comment
https://forums.phpfreaks.com/topic/184567-returning-0-with-count/
Share on other sites

Don't know how you tried it, but this should work and be pretty fast

SELECT
  t1.ID,
  t2.cnt,
  t3.cnt
FROM
  table1 AS t1
LEFT JOIN
  (SELECT t1ID, COUNT(*) AS cnt FROM table2 GROUP BY t1ID) AS t2
USING (t1ID)
LEFT JOIN
  (SELECT t1ID, COUNT(*) AS cnt FROM table3 GROUP BY t1ID) AS t3
USING (t1ID)
WHERE t1ID = 2

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.