分组时订购JOIN结果

时间:2013-02-07 15:07:24

标签: mysql sql join sql-order-by left-join

以下面的例子为例:

SELECT 
    *
FROM 
    auctions AS a 
    LEFT JOIN winners AS w ON a.auction_id=w.auction_id
WHERE 
    a.active=1 
AND 
    a.approved=1 
GROUP BY
    a.auction_id
ORDER BY
    a.start_time DESC
LIMIT
    0, 10;

有时这可能会匹配winners表中的多个结果;我不需要他们两个,但是如果有多个匹配,我想控制我得到哪一行。如何在获奖者桌上进行ORDER BY,以便确保我想要的行是第一个?

2 个答案:

答案 0 :(得分:3)

如果没有看到您的表结构,很难准确回答,但如果您的winners表有一个赢家日期列或类似的东西,那么您可以使用聚合函数来获取第一条记录。

然后您可以返回与此类似的最早日期的记录:

SELECT *
FROM auctions AS a 
LEFT JOIN winners w1
  ON a.auction_id=w1.auction_id
LEFT JOIN
(
  select auction_id, min(winner_date) MinDate -- replace this with the date column in winners
  from winners 
  group by auction_id
) AS w2
  ON a.auction_id=w2.auction_id
  and w1.winner_date = w2.MinDate
WHERE a.active=1 
  AND a.approved=1 
ORDER BY a.start_time DESC

答案 1 :(得分:1)

SELECT *
FROM   auctions AS a
       LEFT JOIN (select auction_id from winners order BY auction_id limit 1) AS w ON a.auction_id = w.auction_id
WHERE  a.active = 1
       AND a.approved = 1
GROUP  BY a.auction_id
ORDER  BY a.start_time DESC

将join子句中对winners表的引用更改为子查询。然后,您可以控制返回的记录数以及按什么顺序。