我有一个评论表(“event_comments”)到不同的事件,其中包含以下列:
我希望能够从数据库中检索此信息,并且还能够打印用户名,名字和姓氏;为此,我考虑使用INNER JOIN,但由于以下原因它无法工作:我有3种不同的配置文件类型(3个不同的表)“学生”,“监护人”,“老师”以及当我尝试使用INNER时使用“用户名”加入我收到一条错误消息,指出from子句中的列'username'是不明确的。
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条评论;如果用户有多个注释,则忽略该信息:
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起作用?有没有更好的方法来做我想要的?我希望我能很好地解释自己。
谢谢!
答案 0 :(得分:1)
每对using
s需要join
子句:
FROM event_comments INNER JOIN
students
USING (username) INNER JOIN
guardians
USING (username) INNER JOIN
teachers
USING (username)
在MySQL中,没有inner join
子句的on
被视为cross join
。在其他数据库中,on
需要using
或inner join
条款。
答案 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
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
编辑: 为了更好地解释查询,它只需执行以下简单步骤: