我有一个针对不同事件的评论表(“event_comments”),包含以下列:
- post_id
- 事件编号
- 用户名
- 评论
- 日期
我希望能够从数据库中检索这些信息,并且能够打印用户名、名字和姓氏;为此,我想到了使用 INNER JOIN,但由于以下原因它不起作用:我有 3 种不同的配置文件类型(3 个不同的表)“学生”、“监护人”、“教师”,当我尝试使用 INNER JOIN using "username"我收到一条错误消息,指出 from 子句中的 Column 'username' is ambiguous。
SELECT event_comments.post_id, event_comments.event_id, event_comments.username, event_comments.comment, event_comments.date,
students.first_name, students.last_name, students.picture,
guardians.first_name, guardians.last_name, guardians.picture,
teachers.first_name, teachers.last_name, teachers.picture
FROM event_comments
INNER JOIN students
INNER JOIN guardians
INNER JOIN teachers
USING (username)
ORDER BY date DESC
LIMIT 20
我尝试这样做并且成功了,但它只显示每个用户 1 条评论;如果用户有超过 1 条评论,则信息将被忽略:
SELECT event_comments.post_id, event_comments.event_id, event_comments.username, event_comments.comment, event_comments.date,
students.first_name, students.last_name, students.picture,
guardians.first_name, guardians.last_name, guardians.picture,
teachers.first_name, teachers.last_name, teachers.picture
FROM event_comments
INNER JOIN students
INNER JOIN guardians
INNER JOIN teachers
GROUP BY username
ORDER BY date DESC
LIMIT 20
有人知道如何让 INNER JOIN 工作吗?有没有更好的方法来做我想做的事?我希望我解释得很好。
谢谢!
最佳答案
这样做:
SELECT event_comments.post_id, event_comments.event_id, event_comments.username, event_comments.comment, event_comments.date,
students.first_name, students.last_name, students.picture,
guardians.first_name, guardians.last_name, guardians.picture,
teachers.first_name, teachers.last_name, teachers.picture
FROM event_comments
INNER JOIN students
on event_comments.username=students.username
INNER JOIN guardians
on event_comments.username=guardians.username
INNER JOIN teachers
on event_comments.username=teachers.username
ORDER BY date DESC
LIMIT 20
这会起作用,但假设一个表中的用户名不存在于其他表中,这将导致 0 行。
一种更合乎逻辑的方法是选择每个表,然后将其合并以连接每个结果集,如下所示:
SELECT e.post_id, e.event_id, e.username, e.comment, e_comments.date,
s.first_name, s.last_name, s.picture
from event_comments e
inner join students s
on e.username=g.username
UNION SELECT e.post_id, e.event_id, e.username, e.comment, e_comments.date,
g.first_name, g.last_name, g.picture
from event_comments e
inner join guardians g
on e.username=g.username
UNION SELECT e.post_id, e.event_id, e.username, e.comment, e_comments.date,
t.first_name, t.last_name, t.picture
from event_comments e
inner join teacher t
on e.username=t.username
编辑: 为了更好地解释查询,它只执行以下简单步骤:
- 查询所有学生使用用户名加入帖子给学生的评论
- 查询所有监护人使用用户名加入监护人的评论
- 查询所有教师使用用户名加入帖子给教师的评论
- 将学生、监护人和老师的结果合并在一起
关于php - 从不同的Mysql表中获取具有相同名称的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26835816/