使用CASE的条件内连接

时间:2016-10-13 08:21:26

标签: mysql sql

我想计算并总结表格中的所有位列,如果它的总和大于2,则isApprove表中的documents列将为1。

SELECT document_id,
SUM(CASE WHEN isApprove = 1 THEN 1 ELSE 0 END) AS approveBy
FROM approvals_document

输出:

document_id | approveBy
     96          2

我想加入approvals_document的相关表格documents使用此表。

SELECT document_id, D.isApprove,
SUM(CASE WHEN isApprove = 1 THEN 1 ELSE 0 END) AS approveBy
FROM approvals_document AD
INNER JOIN documents D ON D.id = AD.document_id

但它不会加入isApprove列。我错过了哪一部分?任何帮助将不胜感激!

approvals_document

id | document_id | isApprove

documents

id | isApprove

草案输出:

document_id | approveBy | isApprove(documents table)

    96           2            0

3 个答案:

答案 0 :(得分:3)

你在连接子句中缺少一个等于ON的,你需要为这个案例添加别名:

SELECT document_id, D.isApprove,
SUM(CASE WHEN AD.isApprove = 1 THEN 1 ELSE 0 END) AS approveBy
FROM approvals_document AD
INNER JOIN documents D ON D.id = AD.document_id

答案 1 :(得分:1)

使用LEFT JOIN AND GROUP BY尝试使用以下查询。

SELECT d.id, 
    d.isApprove,
    SUM(CASE WHEN ad.document_id IS NULL THEN 0 ELSE 1 END) AS approveBy
FROM documents d
LEFT JOIN  approvals_document ad
  ON  ad.isApprove =1 and ad.document_id = d.id
GROUP BY d.id,d.isApprove

答案 2 :(得分:0)

您正在尝试列出所有文件和已批准的数量:

尝试:

SELECT documents.id, 
    documents.isApprove,
    (select count(*) from approvals_document WHERE approvals_document.isApprove =1 and approvals_document.document_id = documents.id) as approveBy
FROM documents;

会给你

+------------+--------------------+--------------------------+
| documet.id | isapproved or not, | number of times approved |
+------------+--------------------+--------------------------+
|          1 |                  1 |                        2 |
+------------+--------------------+--------------------------+