任何人都可以帮我完成这项任务吗?我们说我有两张桌子:
_表1"发布者":ASIN,Price,publisher_ID
_表2"违规":ASIN,publisher_ID,Previous_Violations(Y / N),ID
现在我有了这个
SET @PUB = "
'A','B','C','D',
"
SELECT p.publisher_ID, count(distinct v.id) as "Number of Violations"
FROM Publisher p
LEFT JOIN Violations v
ON p.publisher_ID = v.publisher_ID
and p.Previous_Violations = 'Y'
WHERE
p.publisher_ID IN (",@PUB,")
GROUP BY p.publisher_ID
我想查看@PUB列表中所有发布者的历史记录违规行为。所以会有4个案例:
为了澄清,让我们说酒吧A& B存在于两个表中,C存在于表1中(不是2),D存在于表2中(但不存在于1中),并且E也不存在于表中。
现在我上面的查询仅给出(由于左连接)
A 3
B 2
C 4
但我希望它显示:
A 3
B 2
C 4
D 6
E Null
答案 0 :(得分:0)
如果您没有大型列表,可以尝试以下操作,您可以创建一个为您生成查询的过程
(
SELECT p.publisher_ID, sum(IF(v.Previous_Violations = 'Y', 1, 0)) AS "Number of Violations"
FROM (SELECT 'A' AS publisher_ID) AS p LEFT JOIN Violations v USING(publisher_ID)
GROUP BY p.publisher_ID
)
UNION
(
SELECT p.publisher_ID, sum(IF(v.Previous_Violations = 'Y', 1, 0)) AS "Number of Violations"
FROM (SELECT 'B' AS publisher_ID) AS p LEFT JOIN Violations v USING(publisher_ID)
GROUP BY p.publisher_ID)
UNION
(
SELECT p.publisher_ID, sum(IF(v.Previous_Violations = 'Y', 1, 0)) AS "Number of Violations"
FROM (SELECT 'C' AS publisher_ID) AS p LEFT JOIN Violations v USING(publisher_ID)
GROUP BY p.publisher_ID)
UNION
(
SELECT p.publisher_ID, sum(IF(v.Previous_Violations = 'Y', 1, 0)) AS "Number of Violations"
FROM (SELECT 'D' AS publisher_ID) AS p LEFT JOIN Violations v USING(publisher_ID)
GROUP BY p.publisher_ID
)
UNION
(
SELECT p.publisher_ID, sum(IF(v.Previous_Violations = 'Y', 1, 0)) AS "Number of Violations"
FROM (SELECT 'E' AS publisher_ID) AS p LEFT JOIN Violations v USING(publisher_ID)
GROUP BY p.publisher_ID
)