我有一个如下的SQL查询:
SELECT
a.id user_id, a.type, a.email_address,
a.name_first, a.name_last, languages.title as language,
b.created_at purchased_on, b.expires_at watchable_until,
c.title,
d.title topic,
e.title category,
f.subject, f.grade
FROM users a,
user_video_purchases b,
videos c,
gradesubject_category_topics d,
gradesubject_categories e,
gradesubjects f
JOIN languages ON
users.language_preferred_id = languages.id
WHERE a.id = b.user_id
AND b.video_id = c.id
AND c.gradesubject_category_topic_id = d.id
AND d.gradesubject_category_id = e.id
AND e.gradesubject_id = f.id
ORDER BY purchased_on DESC;
此查询返回以下错误消息:
“ on子句”中的未知列“ users.language_preferred_id”
这些列存在于users
表中,据我所知JOIN
是正确的。
有人可以指出我可能会出问题的地方吗?
答案 0 :(得分:7)
您正在混合使用旧式和现代联接语法。您应该只使用后者:
SELECT a.id user_id, a.type, a.email_address, a.name_first, a.name_last,
l.title as language,
b.created_at purchased_on,
b.expires_at watchable_until,
c.title,
d.title topic,
e.title category,
f.subject, f.grade
FROM users a
INNER JOIN user_video_purchases b
ON a.id = b.user_id
INNER JOIN videos c
ON b.video_id = c.id
INNER JOIN gradesubject_category_topics d
ON c.gradesubject_category_topic_id = d.id
INNER JOIN gradesubject_categories e
ON d.gradesubject_category_id = e.id
INNER JOIN gradesubjects f
ON e.gradesubject_id = f.id
INNER JOIN languages l
ON a.language_preferred_id = l.id
ORDER BY
purchased_on DESC;
答案 1 :(得分:4)
最好使用如下所示的显式联接
SELECT a.id user_id, a.type, a.email_address, a.name_first, a.name_last, languages.title as language,
b.created_at purchased_on, b.expires_at watchable_until,
c.title,
d.title topic,
e.title category,
f.subject, f.grade
FROM users a inner join
user_video_purchases b on a.id = b.user_id
inner join videos c on b.video_id = c.id
inner join gradesubject_category_topics d on c.gradesubject_category_topic_id = d.id
inner join gradesubject_categories e on d.gradesubject_category_id = e.id
inner join gradesubjects f on e.gradesubject_id = f.id
inner JOIN languages l ON a.language_preferred_id = l.id
ORDER BY purchased_on DESC
答案 2 :(得分:2)
Join
based syntax 这是使用显式联接的重做代码:
SELECT a.id AS user_id,
a.type,
a.email_address,
a.name_first,
a.name_last,
g.title AS language,
b.created_at AS purchased_on,
b.expires_at AS watchable_until,
c.title,
d.title AS topic,
e.title AS category,
f.subject,
f.grade
FROM users a
JOIN user_video_purchases b
ON a.id = b.user_id
JOIN videos c
ON b.video_id = c.id
JOIN gradesubject_category_topics d
ON c.gradesubject_category_topic_id = d.id
JOIN gradesubject_categories e
ON d.gradesubject_category_id = e.id
JOIN gradesubjects f
ON e.gradesubject_id = f.id
JOIN languages g
ON a.language_preferred_id = g.id
ORDER BY purchased_on DESC;