在MYSQL复杂查询中使用LIMIT的子查询

时间:2013-02-10 01:35:38

标签: mysql join subquery limit

我正在使用的Mysql版本不要让我在子查询中使用LIMIT,这样我就可以加快查询速度。如何在下一个查询中使用join?

SELECT p . * , (

SELECT AVG( review_rating ) AS rating_total
FROM reviews r
WHERE r.review_item_ref = p.pattern_ref
AND r.review_state =1
GROUP BY r.review_item_ref
) AS review_rating
FROM patterns p
WHERE pattern_active >=0
AND p.pattern_family =27
AND p.pattern_ref
IN (

SELECT item_pattern_ref
FROM items
WHERE item_pattern_ref = p.pattern_ref LIMIT 1
)
GROUP BY p.pattern_id
ORDER BY p.pattern_description ASC , LCASE( p.pattern_description ) ASC
LIMIT 0 , 16

2 个答案:

答案 0 :(得分:0)

看起来你正在尝试验证p.pattern_ref在项目中是否匹配,这是正确的吗?

如果是的话,

SELECT 
    p . *,
    (SELECT AVG( review_rating ) AS rating_total
        FROM reviews r
        WHERE r.review_item_ref = p.pattern_ref
            AND r.review_state =1
        GROUP BY r.review_item_ref
    ) AS review_rating
FROM patterns p
INNER JOIN items i ON p.pattern_ref = i.item_pattern_ref
WHERE p.pattern_active >= 0
    AND p.pattern_family = 27
GROUP BY p.pattern_id
ORDER BY p.pattern_description ASC , LCASE( p.pattern_description ) ASC
LIMIT 0 , 16

应该有效。 INNER JOIN只会返回双方都匹配的行。

答案 1 :(得分:0)

您不能在子查询中使用LIMIT。