我正在尝试查询一个城市最近的商店。
我有这个表(临时表中记录的fac中的查询结果)
id_Customer | id_Shop | distance
-------------------------------
1 | 1 | 10
1 | 2 | 30
1 | 3 | 100
2 | 3 | 150
2 | 2 | 300
2 | 1 | 400
我会得到这个结果(最小距离)
id_Customer | id_Shop | distance
-------------------------------
1 | 1 | 10
2 | 3 | 150
我该怎么做?
答案 0 :(得分:4)
Here是官方MySQL文档中的一篇优秀文章:
引用:
任务:对于每篇文章,找到价格最贵的经销商或经销商。
这个问题可以通过像这样的子查询来解决:
SELECT article, dealer, price
FROM shop s1
WHERE price=(SELECT MAX(s2.price)
FROM shop s2
WHERE s1.article = s2.article);
前面的示例使用相关子查询,这可能是低效的(请参见第13.2.10.7节“相关子查询”)。解决问题的其他可能性是在FROM子句或LEFT JOIN中使用不相关的子查询。
不相关的子查询:
SELECT s1.article, dealer, s1.price
FROM shop s1
JOIN (
SELECT article, MAX(price) AS price
FROM shop
GROUP BY article) AS s2
ON s1.article = s2.article AND s1.price = s2.price;
LEFT JOIN:
SELECT s1.article, s1.dealer, s1.price
FROM shop s1
LEFT JOIN shop s2 ON s1.article = s2.article AND s1.price < s2.price
WHERE s2.article IS NULL;
LEFT JOIN的工作原理是,当s1.price处于最大值时,没有s2.price具有更大的值,s2行值将为NULL。
答案 1 :(得分:2)
select t.id_Customer, t.id_Shop, t.distance
from your_table t
inner join
(
select id_Customer, min(distance) as m_dis
from your_table
group by id_Customer
) x on x.id_Customer = t.id_Customer and t.distance = x.m_dis