我在sql的新手,我想知道为什么这个在我创建我的SQL查询到视图时出错
mysql查询:
SELECT staffid AS staff,
(SELECT count( feedback )FROM msqueue WHERE staffid = staff AND feedback =1) AS a,
(SELECT count( feedback )FROM msqueue WHERE staffid = staff AND feedback =2) AS b,
(SELECT count( feedback )FROM msqueue WHERE staffid = staff AND feedback =3) AS c,
(SELECT count( feedback )FROM msqueue WHERE staffid = staff AND feedback =4) AS d
FROM msqueue
GROUP BY staffid
这个查询结果就像我想要的那样
|staff| a | b | c | d |
|d1111| 0 | 1 | 1 | 0 |
|d1234| 1 | 2 | 4 | 0 |
但是当我创建查询作为视图时 结果是
|staff| a | b | c | d |
|d1111| 1 | 3 | 5 | 0 |
|d1234| 1 | 3 | 5 | 0 |
请帮助我解释这段代码发生的事情..非常感谢
答案 0 :(得分:3)
尝试
SELECT staffid AS staff,
(SELECT count(*) FROM msqueue n WHERE n.staffid = m.staffid AND feedback =1) AS a,
(SELECT count(*) FROM msqueue n WHERE n.staffid = m.staffid AND feedback =2) AS b,
(SELECT count(*) FROM msqueue n WHERE n.staffid = m.staffid AND feedback =3) AS c,
(SELECT count(*) FROM msqueue n WHERE n.staffid = m.staffid AND feedback =4) AS d
FROM msqueue m
GROUP BY staffid
在原始查询中,您使用主要选择列staffid
的别名将其与子查询的staffid
列配对。这不足以区分两列,因此您可以获得每行中所有内容的总和。通过在列名前面使用表别名m
和n
,我们现在可以清楚地解决这两个问题。
列。
见这里:http://sqlfiddle.com/#!9/ab25a9/1
您甚至可以在子查询中省略表别名,例如
SELECT staffid AS staff,
(SELECT count(*) FROM msqueue WHERE staffid = m.staffid AND feedback =1) AS a,
(SELECT count(*) FROM msqueue WHERE staffid = m.staffid AND feedback =2) AS b,
(SELECT count(*) FROM msqueue WHERE staffid = m.staffid AND feedback =3) AS c,
(SELECT count(*) FROM msqueue WHERE staffid = m.staffid AND feedback =4) AS d
FROM msqueue m
GROUP BY staffid
http://sqlfiddle.com/#!9/ab25a9/2
修改强>
毕竟这是"聪明的"从我这边我刚刚发现,你原来的陈述是有效的 - 至少是#34;它自己的#34; (http://sqlfiddle.com/#!9/ab25a9/4)。我还没有尝试过把它放在视图中。当事情开始出错时,也许就是这个问题。更安全的选择肯定是使用表别名。
是的,当你把它放在视图中时,ist 出错了!但是对于外部查询至少有一个表别名,一切正常:http://sqlfiddle.com/#!9/f5f1e/1
我首先使用 MySql 对其进行了测试,但语句相同,并且在 SQL-Server 中的工作方式相同,请参阅此处http://sqlfiddle.com/#!6/f5f1e/1
答案 1 :(得分:2)
我无法访问mysql服务器来测试它,但只是在一般的SQL术语中,这可能是一个更简单的解决方案:
SELECT
staffid AS staff,
SUM(CASE WHEN feedback = 1 THEN 1 ELSE 0 END) AS a,
SUM(CASE WHEN feedback = 2 THEN 1 ELSE 0 END) AS b,
SUM(CASE WHEN feedback = 3 THEN 1 ELSE 0 END) AS c,
SUM(CASE WHEN feedback = 4 THEN 1 ELSE 0 END) AS d
FROM
msqueue
GROUP BY
staffid