我有一张包含斧头的桌子,是的,我还有另一张包含斧头的桌子,以及其他一些东西。
我正在尝试选择总斧数,斧头插入b中,斧头未插入b中。
我有
SELECT
COUNT(a.ax) AS p,
COUNT(a.ax) AS q,
FROM
a
LEFT JOIN b ON a.ay = b.ay
WHERE b.ay is NULL;
这给我一张桌子 - 但两个都是2.我不确定如何在保持左连接的同时分离条件。
感谢任何建议 - 谢谢。
答案 0 :(得分:2)
看来你需要这样的东西:
SELECT
COUNT(*) AS total,
COUNT(r.hnum) AS inserted
FROM
h
LEFT JOIN r ON h.hnum = r.hnum;
或者你可以使用条件聚合:
SELECT
COUNT(*) AS total,
SUM(CASE WHEN r.hnum IS NULL THEN 1 ELSE 0 END) As noninserted,
SUM(CASE WHEN r.hnum IS NULL THEN 0 ELSE 1 END) As inserted
FROM
h
LEFT JOIN r ON h.hnum = r.hnum;
此处有SQLFiddle Demo条件聚合。
处理r
中的重复项:
SELECT
COUNT(*) AS total,
SUM(CASE WHEN r.hnum IS NULL THEN 1 ELSE 0 END) As noninserted,
SUM(CASE WHEN r.hnum IS NULL THEN 0 ELSE 1 END) As inserted
FROM
h
LEFT JOIN (SELECT DISTINCT hnum FROM r) r ON h.hnum = r.hnum;
这里的SQLFiddle Demo用于带有重复项的条件聚合。
带有计算字段的 JOIN
和COUNT (DISTINCT)
:
SELECT result.total As "Total",
result.inserted as "Inserted",
result.total - result.inserted as "Noninserted"
FROM
( SELECT
COUNT(DISTINCT h.hnum) AS total,
COUNT(DISTINCT r.hnum) AS inserted
FROM
h
LEFT JOIN r ON h.hnum = r.hnum ) result;
以及此Fiddle