我不确定如何从连接表中返回最高值。表中当前有4个项目,但查询只返回一个。 MAX(b.bid)正在打破查询。
SELECT i.id,
i.user_id,
i.item_title,
i.item_description,
i.item_condition,
i.active,
i.add_date,
MAX(b.bid)
FROM items i
LEFT JOIN bids b
ON i.id = b.item_id
WHERE i.user_id = ? AND i.active = 1
ORDER BY i.id DESC
答案 0 :(得分:0)
你可能想要这样的东西:
SELECT i.id,
i.user_id,
i.item_title,
i.item_description,
i.item_condition,
i.active,
i.add_date,
b.bid
FROM items i
LEFT JOIN (SELECT MAX(bid) AS bid, item_id
FROM bids
GROUP BY item_id) b
ON i.id = b.item_id
WHERE i.user_id = ? AND i.active = 1
ORDER BY i.id DESC
您获得bid
每item_id
的最大值,然后执行LEFT JOIN
操作。
答案 1 :(得分:0)
如果我理解你的问题,你需要一个group by
条款:
SELECT i.id,
i.user_id,
i.item_title,
i.item_description,
i.item_condition,
i.active,
i.add_date,
MAX(b.bid)
FROM items i
LEFT JOIN bids b
ON i.id = b.item_id
WHERE i.user_id = ? AND i.active = 1
group by i.id,
i.user_id,
i.item_title,
i.item_description,
i.item_condition,
i.active,
i.add_date
ORDER BY i.id DESC
答案 2 :(得分:0)
你可以这样做:
SELECT i.id,
i.user_id,
i.item_title,
i.item_description,
i.item_condition,
i.active,
i.add_date,
b.bid
FROM items i
LEFT JOIN
(
SELECT
MAX(bids.bid) as bid,
bids.item_id
FROM
bids
GROUP BY
bids.item_id
) as b
ON i.id = b.item_id
WHERE i.user_id = ? AND i.active = 1
ORDER BY i.id DESC
答案 3 :(得分:0)
如果您想要每个项目max(bid)
,那么您需要逐项group
查询。
SELECT i.id,
i.user_id,
i.item_title,
i.item_description,
i.item_condition,
i.active,
i.add_date,
MAX(b.bid)
FROM items i
LEFT JOIN bids b
ON i.id = b.item_id
WHERE i.user_id = ? AND i.active = 1
GROUP BY i.id
ORDER BY i.id DESC
此结果取决于每个出价的所有其他字段是相同的,它看起来应该是这样。这是对group by
的mysql扩展的有效使用。否则,您需要在group by
子句中的select中指定每个字段。