gpt4 book ai didi

mysql - 与mysql水平连接

转载 作者:行者123 更新时间:2023-11-30 22:38:46 27 4
gpt4 key购买 nike

我正在尝试查询 2 个表,一个包含学生,另一个包含与学生相关的评论。

学生表:

| ID | Name |
-------------
| 1 | John |
| 2 | Alex |

评论表:

| ID | Student ID | Comment |
-----------------------------
| 1 | 1 | phoned |
| 2 | 1 | emailed |
| 3 | 2 | phoned |
| 4 | 2 | emailed |
| 5 | 2 | mailed |

我想要的输出是这样的:

| Student | Comment 3 | Comment 2 | Comment 1 |
-----------------------------------------------
| John | null | phoned | emailed |
| Alex | mailed | emailed | called |

如有任何帮助,我们将不胜感激。

最佳答案

一种方法如下:

SELECT students.name, c1.comment, c2.comment, c3.comment FROM students
LEFT JOIN (SELECT * FROM comments WHERE comment = 'phoned') as c1
ON c1.student_id = students.id
LEFT JOIN (SELECT * FROM comments WHERE comment = 'emailed') as c2
ON c2.student_id = students.id
LEFT JOIN (SELECT * FROM comments WHERE comment = 'mailed') as c3
ON c3.student_id = students.id

您必须增加每种评论类型的加入数量。

关于mysql - 与mysql水平连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31673564/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com