将LIMIT应用于SQL INNER JOIN查询

时间:2015-05-20 13:18:26

标签: mysql

我有以下表格:

CATEGORY

    id(int)
    1000  
    1001

图书

    id(int)  category(int) rating(float)
    3000     1000          5.0
    3001     1000          4.8
    3002     1000          3.0
    3003     1000          4.9
    3004     1001          4.9
    3005     1001          3.0

我想要做的是从每个类别中获取3本最受欢迎的书籍。在环顾四周并按照LIMITing an SQL JOIN给出的答案后,我尝试了这个查询。

    SELECT * FROM book, category WHERE book.category=category.id AND book.id IN (SELECT book.id FROM book ORDER BY rating LIMIT 3)

但它会出现以下错误

     #1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

该解决方案表示至少需要 MySQL 5.1 ,并且我正在运行 libmysql - 5.1.73 。什么可能是错的?

3 个答案:

答案 0 :(得分:1)

MySQL抱怨IN,而不是LIMIT。将IN更改为INNER JOIN,它应该有效。

像这样的查询:

SELECT * FROM book b, category INNER JOIN (SELECT id FROM book ORDER BY rating LIMIT 3) v
ON b.id=v.id
WHERE b.category=category.id;

答案 1 :(得分:0)

MySQL在某些子查询运算符的子查询中不支持LIMIT

'LIMIT & IN/ALL/ANY/SOME subquery'

例如

mysql> SELECT * FROM t1
    ->   WHERE s1 IN (SELECT s2 FROM t2 ORDER BY s1 LIMIT 1);
ERROR 1235 (42000): This version of MySQL doesn't yet support
 'LIMIT & IN/ALL/ANY/SOME subquery'

阅读子查询limitation

答案 2 :(得分:0)

有一个技巧可以将LIMIT 3更改为LIMIT 0,3:就像这样:

 SELECT * FROM book, category WHERE book.category=category.id 
        AND book.id IN (SELECT book.id FROM book ORDER BY rating LIMIT 0,3)

Source ^^