我正在使用像这样的mysql进行lefjoin咨询
SELECT A.*,B.*,C.*,D.*
from TableA A
left join TableB B on A.id=B.id
left join TableC C on A.id=C.id
left join TableD D on A.id=D.id
where
//some condition
//group by
//order by
最终结果是一维数组,但有些值没有数据,例如我有一些值B.Value1: null
,C.Value1: null
,B.Value2: null
等。
我正在寻找,只计算有数据的表,Eq。
id=20
,B表格为空白,因此此ID的结果应为3(A,C和D)id=22
,C表格为空白,因此此ID的结果应为2(A和B)注意:
答案 0 :(得分:2)
我不确定这是否是您要找的,但我假设您想要获得2列的结果。在第一列中,您需要在A和第二列中显示的ID,您需要ID出现的表的数量。如果是这样,这应该有效...
SELECT id, count(*) as num
FROM (
SELECT A.id FROM TableA A
UNION ALL
SELECT B.id FROM TableB B
UNION ALL
SELECT C.id FROM TableC C
UNION ALL
SELECT D.id FROM TableD D
) mytables
group by id
答案 1 :(得分:1)
您可能希望查询使用union all
和group by
:
select id, count(distinct which) as NumTablesWithValue
from ((select id, value, 'a' as which from tableA) union all
(select id, value, 'b' from tableb) union all
(select id, value, 'c' from tablec) union all
(select id, value, 'd' from tabled)
) i
group by id;