0

以下面为例:

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在获胜者表上进行操作,以确保我想要的行是第一行?

4

2 回答 2

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
于 2013-02-07T15:15:02.460 回答
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

将连接子句中对获胜者表的引用更改为子查询。然后,您可以控制返回的记录数量和顺序。

于 2013-02-07T15:14:28.203 回答