mysql - Join multiple tables where id may not exist -
i have 2 tables follows:
table_a: id, title table_b: id, table_a_id, status
i want select total number of entries in table_b each value of table_a, total number of entries in table_b not reference table_a.
for example, let's table_a has values:
{id, title} (1, "value 1") (2, "value 2") (3, "value 3")
and table_b has following entries
{id, table_a_id, status} (1, 1, 'open') (2, 1, 'closed') (3, -, 'open') (4, 2, 'closed')
what trying along lines of:
("value 1", 2) ("value 2", 1) ("value 3", 0) (-, 1)
without nulls, write as:
select table_a.id, table_a.title, count(table_b.id) table_a left join table_b on table_a.id = table_b.table_a_id group table_a.id, table_a.title
however, doesn't give me values entries in table_b not reference table_a. if reverse join, can values table_b, not table_a. how can both in single query?
i'm using sql server, guess it'll work on mysql too. important here coalesce
function, and mysql runs same way sql server does.
select coalesce(a.title, '-'), count(b.id) #table_b b left join #table_a on b.table_a_id = a.id group a.title union select a.title, 0 #table_a left join #table_b b on b.table_a_id = a.id b.id null
Comments
Post a Comment