我正在尝试找出一个SQL查询以一次从多个表中提取数据。香港专业教育学院有一张桌子,上面有公司清单。我还有另外两个表,其中包含每个公司的通讯。目前,我正在遍历每个公司行,然后对每个通讯表执行查询。 我试过像这样的查询:
SELECT c.*,
count(e.id) AS ecount,
count(p.id) AS pcount
FROM companies c
LEFT JOIN emails e
ON c.id = e.company
LEFT JOIN push p
ON c.id = p.company
但是此查询的结果仅包含一个公司,没有计数。如何完成此查询?
答案 0 :(得分:0)
您可能打算:
SELECT c.*,
count(distinct e.id) AS ecount,
count(distinct p.id) AS pcount
FROM companies c LEFT JOIN
emails e
ON c.id = e.company LEFT JOIN
push p
ON c.id = p.company
GROUP BY c.id;
假设companies.id
是唯一键或主键,那么这是表达逻辑的有效方法。
答案 1 :(得分:0)
SELECT c.*,
(SELECT COUNT(e.id) FROM emails e WHERE e.company = c.id) as ecount,
(SELECT COUNT(p.id) FROM push p WHERE p.company = c.id) as pcount
FROM companies c
答案 2 :(得分:0)
SELECT c.*,
( SELECT count(e.id) FROM emails WHERE e.company = c.id ) AS ecount,
...
FROM companies c