ORDER BY破解mysql查询

时间:2012-04-14 00:56:47

标签: php mysql join sql-order-by inner-join

这里有人帮助整理了这个非常有用的查询!

SELECT * FROM results r 
INNER JOIN categories c on r.id = c.result_id 
WHERE c.name in ('$purpose', '$prop_type', '$loan_type')
GROUP BY r.id
HAVING COUNT(c.c_id) = 3
LIMIT 50 OFFSET 0

哪个好极了!但是,当我尝试使用

命令结果时
SELECT * FROM results r 
INNER JOIN categories c on r.id = c.result_id 
WHERE c.name in ('$purpose', '$prop_type', '$loan_type')
ORDER BY r.usefulness DESC
GROUP BY r.id
HAVING COUNT(c.c_id) = 3
LIMIT 50 OFFSET 0

我收到语法错误。我错过了一些明显的东西吗?

非常感谢!

2 个答案:

答案 0 :(得分:3)

查询的各个部分有一个订单,ORDER BY应该在最后(LIMITOFFSET之前......试试这个:

SELECT * FROM results r 
INNER JOIN categories c on r.id = c.result_id 
WHERE c.name in ('$purpose', '$prop_type', '$loan_type')
GROUP BY r.id
HAVING COUNT(c.c_id) = 3
ORDER BY usefulness DESC
LIMIT 50 OFFSET 0

还要确保在任何行的末尾都有空格......

注意在mysql中LIMIT x OFFSET y的缩短版本 - 你可以写LIMIT y,x

答案 1 :(得分:1)

ORDER BY必须在HAVING

之后