除了自我加入,还有其他选择吗?

时间:2018-12-14 16:28:39

标签: sql postgresql

我正在查询。

SELECT 
   v.id,
   v.type,
   COUNT(vn.id) as notice_sent_count,
   COUNT(vn1.id) as total_count
FROM 
     vln v 
     LEFT JOIN notes vn ON(v.note_id = vn.id AND vn.note_datetime IS NOT NULL)
     LEFT JOIN notes vn1 ON(v.note_id = vn1.id)
WHERE 
     v.id = 1
GROUP BY 
     v.id,
     v.type;

使用自我加入,我可以达到notice_sent_count和总数。无论如何,有没有自我加入就可以实现同样的目标。我正在尝试删除第3个加入。有想法吗?

Sample data 
------------------------------------------
v.id v.type notice_sent_count total_count
------------------------------------------
1    type1        2               5
2    type2        1               3

2 个答案:

答案 0 :(得分:2)

您可以使用FILTER

SELECT 
   v.id,
   v.type,
   COUNT(vn.id) FILTER (WHERE vn.note_datetime IS NOT NULL) AS notice_sent_count,
   COUNT(vn.id) AS total_count
FROM  vln v 
LEFT JOIN notes vn ON v.note_id = vn.id
WHERE v.id = 1
GROUP BY  v.id, v.type;

或更简单的fsprojects/FSharp.Interop.Dynamic建议:

SELECT 
   v.id,
   v.type,
   COUNT(vn.note_datetime) AS notice_sent_count,
   COUNT(vn.id) AS total_count
FROM  vln v 
LEFT JOIN notes vn ON v.note_id = vn.id
WHERE v.id = 1
GROUP BY  v.id, v.type;

答案 1 :(得分:1)

您也可以使用CASE

SELECT 
   v.id,
   v.type,
   SUM(CASE WHEN vn.note_datetime IS NULL THEN 0 ELSE 1 END) AS notice_sent_count,
   COUNT(vn.id) AS total_count
FROM  vln v 
LEFT JOIN notes vn ON v.note_id = vn.id
WHERE v.id = 1
GROUP BY  v.id, v.type;