MySQL选择ID匹配的另一个表的行的计数

时间:2015-10-19 16:29:31

标签: mysql

我正在尝试从一个表中选择另一个表的计数,其中id与原始tableID类似:

select *, (count(0) from table2 where table2.table1ID = table1.table1ID) count
    from table1

这是什么mySQL语法?

2 个答案:

答案 0 :(得分:0)

select
  table1.*,
  if(table2.table1ID is null,0,count(*))
from
  table1
  left join table2 on table1.table1ID = table2.table1ID
group by
  table1.table1ID;

答案 1 :(得分:0)

SELECT COUNT(b.*) FROM table1 as a
LEFT JOIN table2 as b ON a.tableID = b.tableID