我有下表:
+---------+--------------+----------+
| item_id | location_id | price |
+---------+--------------+----------+
| 1 | 1 | 100 |
| 1 | 1 | 250 |
| 1 | 2 | 50 |
| 2 | 1 | 250 |
| 2 | 1 | 1000 |
| 3 | 1 | 1000 |
| 3 | 2 | 100 |
+---------+--------------+----------+
我可以使用此查询将其减少到最小值
SELECT
item_id, location_id, MIN(price) AS Price
from
table
GROUP BY item_id , location_id
这让我很感动
+---------+--------------+----------+
| item_id | location_id | price |
+---------+--------------+----------+
| 1 | 1 | 100 |
| 1 | 2 | 50 |
| 2 | 1 | 250 |
| 3 | 1 | 1000 |
| 3 | 2 | 100 |
+---------+--------------+----------+
我想进一步减少这个。我使用 location_id 为 1 的行作为引用行。对于具有与引用行的 item_id 匹配但位置 id 不同的 item_id 的每一行。我想将该行的价格与引用行的价格进行比较。如果价格低于引用行的价格,我想过滤掉该行。
我的最终结果应包括每个商品 ID 的引用行以及满足价格低于引用行价格条件的任何行。
我有预感可以使用 HAVING 子句来执行此操作,但我在编译该语句时遇到了问题。我应该如何构造 HAVING 语句?
提前致谢
最佳答案
不,having 不能帮助你这样的事情,having 是为了像你需要过滤 min() 结果之类的事情
例如:
select id,min(price) from table where date = '2016-3-18' group by id having min(price) = 50
它会显示min(price)=50的记录
让我们回到你的例子,有很多方法可以做到这一点,
<强>1。左连接
select a.item_id,a.location_id,a.price
from table a
left join table b
on a.location_id = b.location_id and a.price > b.price
where b.price is null
<强>2。存在
select a.item_id,a.location_id,a.price
from table a
where exists(
select 1 from
(select location_id,min(price)as price from table group by location_id)b
where a.location_id = b.location_id and a.price = b.price
)
通常我会建议你使用exists
关于mysql - 使用 HAVING 根据引用行过滤结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36077146/