简体   繁体   中英

Can't figure out the error in the mysql query

I am trying for an hour now but I am still not able to figure out what's the problem in this query. :/

SELECT * FROM question ORDER BY question_id DESC LIMIT 3 WHERE topic_name = (SELECT * FROM topic WHERE subject_name = 'Maths')

This is the error:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE topic_name = (SELECT * FROM topic WHERE subject_name = 'Maths')' at line 1

Your statements are all out of order. The correct statement is:

SELECT *
FROM question
WHERE topic_name = (SELECT * FROM topic WHERE subject_name = 'Maths')
ORDER BY question_id DESC LIMIT 3 ;

However, that won't work because of the subquery. Perhaps you mean something like:

SELECT *
FROM question
WHERE topic_name in (SELECT topic_name FROM topic WHERE subject_name = 'Maths')
ORDER BY question_id DESC LIMIT 3 ;

您的WHERE子句需要放在ORDER BY子句之前:

SELECT * FROM question WHERE topic_name IN (SELECT topic_name FROM topic WHERE subject_name = 'Maths') ORDER BY question_id DESC LIMIT 3

Specify which column and Limit the result to one or use the IN operator instead

SELECT * FROM question 
WHERE topic_name = (SELECT topic FROM topic WHERE subject_name = 'Maths')
ORDER BY question_id DESC LIMIT 1 

SELECT * FROM question 
WHERE topic_name in(SELECT topic FROM topic WHERE subject_name = 'Maths')
ORDER BY question_id DESC LIMIT 3 

Actually this is not optimal advice. Do a inner join instead:

SELECT * FROM question q
INNER JOIN topic t 
ON q.topic_name = t.topic
WHERE subject_name = 'Maths'
ORDER BY question_id LIMIT 3 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM