在查询中计数两次,一次使用限制
给出下表:
Table1
[class] [child]
math boy1
math boy2
math boy3
art boy1
Table2
[child] [glasses]
boy1 yes
boy2 yes
boy3 no
如果我想查询每个班级的儿童人数,我会这样做:
SELECT class, COUNT(child) FROM Table1 GROUP BY class
如果我想查询每个班级戴眼镜的儿童人数,我会这样做:
SELECT Table1.class, COUNT(table1.child) FROM Table1
LEFT JOIN Table2 ON Table1.child=Table2.child
WHERE Table2.glasses='yes' GROUP BY Table1.class
但我真正想要的是做的是:
SELECT class, COUNT(child), COUNT(child wearing glasses)
坦率地说,我不知道如何在一个查询中做到这一点。
帮助?
Given the following tables:
Table1
[class] [child]
math boy1
math boy2
math boy3
art boy1
Table2
[child] [glasses]
boy1 yes
boy2 yes
boy3 no
If I want to query for number of children per class, I'd do this:
SELECT class, COUNT(child) FROM Table1 GROUP BY class
and if I wanted to query for number of children per class wearing glasses, I'd do this:
SELECT Table1.class, COUNT(table1.child) FROM Table1
LEFT JOIN Table2 ON Table1.child=Table2.child
WHERE Table2.glasses='yes' GROUP BY Table1.class
but what I really want to do is:
SELECT class, COUNT(child), COUNT(child wearing glasses)
and frankly I have no idea how to do that in only one query.
help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你可以尝试这样的事情(不检查语法):
这有点老套,你可能会发现在两个查询中完成它更容易,但这种技术在紧要关头对我有用
You can try something like this (not syntax checked):
It's a bit hacky and you may find it's just easier to do it in two queries but this technique has worked for me in a pinch
在 MySQL 中,你可以这样做:
SELECT class, COUNT(child), SUM(IF(glasses = 'yes', 1, 0)
in MySQL you can do it something like this:
SELECT class, COUNT(child), SUM(IF(glasses = 'yes', 1, 0)
它不是一个完美的解决方案,它只是一个替代解决方案,
输出是:
在此,我们可能会得到一些开发更多东西的想法。
It is not a perfect solution, it is just a alternative solution,
The output is :
In this, we may got some idea for develop more thing.
也许这个帖子已经有 5 年历史了,但我也有一个解决方案。
使用 1 和 0 等数字来表示是/否和真/假对您来说会更容易。
解决方案是(如果将是和否更改为 1 和 0):
必须检查语法,但我对表有类似的查询并且它有效。
Maybe the post is 5 years old but I ahve also a solution.
Working with digits like 1 and 0 for yes/no and true/false will be easier for you.
A solution would be (if you change the yes's and no's to 1 and 0):
Syntax have to be checked, but I have a similar query for my tables and it works.