我需要获得Max bid和该用户名,但结果却出错了
这是我的两张表
产品
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上?
答案 0 :(得分: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
你得到了奇怪的结果,因为MySQL使用Extension to GROUP BY允许你在不使用GROUP BY的情况下使用聚合函数,但这可能导致你的结果不正确。
GROUP BY使得你将为你所分组的每个项目返回max(bid)
,在你的情况下它是name
和`用户名。
如果您只想为每个产品ID返回一个max(bid)
,那么您可以使用:
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'
答案 1 :(得分: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;
答案 2 :(得分: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;
答案 3 :(得分:-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)