-1

我需要获得最高出价和该用户名,但结果以错误的方式出现

这是我的两张桌子

产品

id | name | username 
 1 |  A   |   deen 
 2    B   |   ann

投标

id | c_bid | username 
 1 |   10  |   ann
 1 |   12  |   ann
 1 |   13  |   ann
 2 |   10  |   ann
 1 |   15  |   Hel
 1 |   16  |   Hel 

SQL

  SELECT name, bid.username AS username, MAX(bid.c_bid) AS c_bid FROM product INNER JOIN bid
    ON  gems.id= bidding.id  WHERE bid.id = '1' 

结果

  name | c_bid | username 
    A  |   16  |   ann 

为什么这个结果会出现在这个 sql 上?

4

4 回答 4

2

由于您使用的是聚合函数,因此您需要包含一个 GROUP BY。

SELECT name, 
  bid.username AS username, 
  MAX(bid.c_bid) AS c_bid 
FROM product 
INNER JOIN bid
  ON  product.id= bid.id  
WHERE bid.id = '1' 
GROUP BY name, bid.username

请参阅带有演示的 SQL Fiddle

您会得到奇怪的结果,因为 MySQL 使用了GROUP BY 的扩展,它允许您在不使用 GROUP BY 的情况下使用聚合函数,但这可能会导致您的结果不正确。

GROUP BY 使您可以返回max(bid)分组依据的每个项目,在您的情况下它是name和 `username.

如果您只想max(bid)为每个产品 id 返回一个,那么您可以使用:

SELECT name, 
  bid.username AS username,
  bid.c_bid
FROM product 
INNER JOIN bid
  ON  product.id= bid.id  
INNER JOIN
(
  SELECT max(c_bid) c_bid, id
  FROM bid
  GROUP BY id
) b
  on bid.id = b.id
  and bid.c_bid = b.c_bid
WHERE bid.id = '1' 

请参阅带有演示的 SQL Fiddle

于 2013-11-07T19:38:30.183 回答
0

使用 GROUP BY。

SELECT name, bid.username AS username, MAX(bid.c_bid) AS c_bid FROM product INNER JOIN bid
    ON  gems.id= bidding.id  WHERE bid.id = '1' GROUP BY bid.username;
于 2013-11-07T19:37:32.297 回答
0
SELECT
    p.username,
    MAX(b.c_bid) AS max_c_bid
FROM product p
LEFT JOIN bid b ON (p.username = b.username)
GROUP BY p.username;
于 2013-11-07T19:38:08.997 回答
-1
SELECT
    pr.name,
    mb.c_bid,
    pr.username
FROM
(
    SELECT
        SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY c_bid DESC), ',', 1) AS id,
        MAX(c_bid) AS c_bid
    FROM bid
    GROUP BY id
) AS mb
JOIN product AS pr ON(pr.id = mb.id)

示例:http ://sqlfiddle.com/#!2/0a6c9/2

于 2013-11-07T20:00:44.110 回答