[英]Selecting a subset of rows from a PHP table
I'm pretty new to using SQL, so I was hoping someone could point me in the right direction for setting up a slightly more complex query than I have needed to use in the past. 我对使用SQL还是很陌生,所以我希望有人可以指出正确的方向来设置比过去需要使用的稍微复杂的查询。
I have a simple mySql table representing a market for a game, which looks like this: (numbers for the purposes of examples later: 我有一个表示游戏市场的简单mySql表,它看起来像这样:(数字用于后面的示例:
id seller price amount
1 tom 330 100
2 tom 370 500
3 tom 400 750
4 jerry 700 250
currently I am loading this table using php: 目前,我正在使用php加载此表:
$items = dbquery("SELECT *
FROM $marketdb
WHERE price=$minprice
ORDER BY amount;");
This is fine, but what I would like to do instead is to only load one row per seller: in particular, I would like to load only the row with the largest value of 'amount' for each seller. 很好,但是我想做的是每个卖方只加载一行:特别是,我只想为每个卖方仅加载'amount'值最大的行。 In the example above, this means the result would only contain the last two lines in the table.
在上面的示例中,这意味着结果将仅包含表中的最后两行。
You can have a subquery which separately get the greatest amount for every seller and join it with the table again to get the extra columns. 您可以有一个子查询,该子查询分别为每个卖方获取最大的金额,然后再次将其与表格结合以获取额外的列。
SELECT a.*
FROM tableName a
INNER JOIN
(
SELECT seller, MAX(amount) amount
FROM tableName
GROUP BY seller
) b ON a.seller = b.seller AND
a.amount = b.amount
or 要么
SELECT a.*
FROM tableName a
WHERE a.amount =
(
SELECT MAX(amount)
FROM tableName b
WHERE a.seller = b.seller
)
both queries will OUTPUT 两个查询都将输出
╔════╦════════╦═══════╦════════╗
║ ID ║ SELLER ║ PRICE ║ AMOUNT ║
╠════╬════════╬═══════╬════════╣
║ 3 ║ tom ║ 400 ║ 750 ║
║ 4 ║ jerry ║ 700 ║ 250 ║
╚════╩════════╩═══════╩════════╝
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.