3

嗨,我有一个查询,它通过显示首先被评分的评论然后是尚未被评分的评论来完成我想要的操作。但是我似乎无法正确订购。

结果应该是什么样子:

5
4
0
0
...

目前它正在这样做:

4
5
0
0
...

这是我的查询

$sql = $db->query( "
    SELECT branch.*, MAX(review.rating) AS m
    FROM branch
    LEFT OUTER JOIN review ON branch.bid = review.bid
    WHERE branch.address2 LIKE '$query' OR branch.postcode LIKE '$query-%'
    GROUP BY branch.bid
    ORDER BY m DESC, branch.branch ASC
    LIMIT $start,$limit 
" ) or die( "Select failed: (" . $db->errno . ") " . $db->error );
4

1 回答 1

1

Meghraj Choudhary 的子查询解决方案应该可以工作。

但是,联接更快。子查询需要额外的磁盘访问。假设branch.bid是主键,以下应该更快:

SELECT b1.*, b2.m FROM branch b1
INNER JOIN
(
SELECT branch.bid, MAX(review.rating) AS m
FROM branch
LEFT OUTER JOIN review ON branch.bid = review.bid
WHERE branch.address2 LIKE '$query' OR branch.postcode LIKE '$query-%'
GROUP BY branch.bid
LIMIT $start,$limit
) b2 ON
b1.bid = b2.bid
ORDER BY b2.m DESC, b1.branch ASC

我没有试过这个。所以,请尝试并回帖。

于 2013-09-06T14:55:34.637 回答