2个查询分别工作良好,但结合使用会产生语法错误

时间:2018-12-04 17:09:35

标签: mysql where

第一个查询涉及与特定主题相关的书籍和作者的列表,并产生正确的结果:

SELECT BOOK_NUM,
BOOK_TITLE,
BOOK_SUBJECT,
AU_LNAME
FROM BOOK
JOIN WRITES USING (BOOK_NUM)
JOIN AUTHOR USING (AU_ID)
WHERE BOOK_SUBJECT = 'CLOUD'
ORDER BY BOOK_TITLE;

第二个扩展了主题,并产生了正确的结果:

SELECT BOOK_NUM,
BOOK_TITLE,
BOOK_SUBJECT,
AU_FNAME,
AU_LNAME,
Count(BOOK_TITLE) AS `NUM BOOKS BY AUTHOR`
FROM BOOK
JOIN WRITES USING (BOOK_NUM)
JOIN AUTHOR USING (AU_ID)
GROUP BY BOOK_NUM, AU_ID
ORDER BY `NUM BOOKS BY AUTHOR`,
AU_LNAME;

当我将两者结合时,会在WHERE BOOK_SUBJECT ='CLOUD'处产生语法错误:

SELECT BOOK_NUM,
BOOK_TITLE,
BOOK_SUBJECT,
AU_FNAME,
AU_LNAME,
Count(BOOK_TITLE) AS `NUM BOOKS BY AUTHOR`
FROM BOOK
JOIN WRITES USING (BOOK_NUM)
JOIN AUTHOR USING (AU_ID)
GROUP BY BOOK_NUM, AU_ID
WHERE BOOK_SUBJECT = 'CLOUD'
ORDER BY `NUM BOOKS BY AUTHOR`, 
AU_LNAME,
BOOK_TITLE;

无论放置在哪里,都会出现相同的错误,如果将其删除,代码将运行。我需要做什么来解决这个问题?我需要将此where子句包括在内。预先感谢您对我的帮助。

2 个答案:

答案 0 :(得分:0)

不确定所使用的SQL。尝试将WHERE子句移到GROUP BY上方。

答案 1 :(得分:0)

好问题。尝试参考一些有关表达式顺序的文档...

请尝试以下代码,在其中适当地移动了WHERE语句。

SELECT 
BOOK_NUM,
BOOK_TITLE,
BOOK_SUBJECT,
AU_FNAME,
AU_LNAME,
Count(BOOK_TITLE) AS `NUM BOOKS BY AUTHOR`

FROM BOOK
JOIN WRITES USING (BOOK_NUM)
JOIN AUTHOR USING (AU_ID)

WHERE BOOK_SUBJECT = 'CLOUD'

GROUP BY BOOK_NUM, AU_ID

ORDER BY `NUM BOOKS BY AUTHOR`, 
AU_LNAME,
BOOK_TITLE;