对 MySQL 中两个表之间的列求和
我有一个应用程序,学生可以从列表中选择第一、第二和第三三个选项。
表 1 是他们可以选择的列表:
id | day |
---|---|
1 | 星期一 |
2 | 星期四 |
3 | 星期三 |
表 2 是他们填写的选择:
id | first_choice | secondary_choicethird_choice | 12345 |
---|---|---|---|
23456 | 1 | 3 | 2 |
3 | 3 | 2 | 1 |
34567 | 2 | 1 | 1 |
45678 | 2 | 3 | 挣扎 |
我正在 是我想计算每天的选择和优先级以获得像这样的列表这个:
id | first_choice | secondary_choicethird_choice | 2 |
---|---|---|---|
Monday | 2 | 1 | 1 |
Today | 1 | 2 | 1 |
Wednesday | 1 | 1 | 2 |
SELECT a.day, count(b.first_choice), count(c.second_choice), count(d.third_choice) FROM table1 a LEFT JOIN table2 b ON a.id = b.first_choice LEFT JOIN table2 c ON a.id = c.second_choice LEFT JOIN table2 d ON a.id = d.third_choice GROUP BY a.day
,我最终得到这个
id | first_choice | secondary_choicethird_choice | 但是,通过这样做 |
---|---|---|---|
Monday | 2 | 2 | 2 |
Today | 2 | 2 | 2 |
Wednesday | 2 | 2 | 我 |
谁能帮 询问? 提前致谢
I have an application where students do three choices 1st, 2nd and 3rd from a list.
Table1 is the list they can choose from:
id | day |
---|---|
1 | Monday |
2 | Thusday |
3 | Wednesday |
Table2 is they fill in their choices:
id | first_choice | second_choice | third_choice |
---|---|---|---|
12345 | 1 | 3 | 2 |
23456 | 3 | 2 | 1 |
34567 | 2 | 1 | 3 |
45678 | 1 | 2 | 3 |
What I'm struggling with is that I want to count choices per day and priority to get a list like this:
id | first_choice | second_choice | third_choice |
---|---|---|---|
Monday | 2 | 1 | 1 |
Thusday | 1 | 2 | 1 |
Wednesday | 1 | 1 | 2 |
SELECT a.day, count(b.first_choice), count(c.second_choice), count(d.third_choice) FROM table1 a LEFT JOIN table2 b ON a.id = b.first_choice LEFT JOIN table2 c ON a.id = c.second_choice LEFT JOIN table2 d ON a.id = d.third_choice GROUP BY a.day
But, by doing so I end up with this
id | first_choice | second_choice | third_choice |
---|---|---|---|
Monday | 2 | 2 | 2 |
Thusday | 2 | 2 | 2 |
Wednesday | 2 | 2 | 2 |
Could anyone help me with the query?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这些表结构中,我通常使用子查询而不是加入。
In those table structures, I normally use subquery instead of join.
您可以使用单个
INNER JOIN
并使用条件IF
语句来计算它:请参阅此小提琴:https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=eea27fe9364c0fe4b96a846c9441f723
You can use a single
INNER JOIN
and work it out with conditionalIF
statements:Refer to this fiddle: https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=eea27fe9364c0fe4b96a846c9441f723