我试图将这个问题从骨头上剥下来;我希望我仍然抓住了我在原始查询中想要达到的目标的本质!
原始表格
+-----------+----------+----------+
| master_id | slave_id | distance |
+-----------+----------+----------+
| 1 | 1 | 0.1 |
| 1 | 3 | 10 |
| 2 | 2 | 3 |
| 3 | 2 | 2 |
+-----------+----------+----------+
需要说明
我想选择slave_id
master_id
对MIN(distance)
与无重复 master_id
或slave_id
。< / p>
所需的结果表
+-----------+----------+----------+
| master_id | slave_id | distance |
+-----------+----------+----------+
| 1 | 1 | 0.1 |
| 3 | 2 | 2 |
+-----------+----------+----------+
我的尝试
SELECT
join_table.master_id,
join_table.slave_id,
join_table.distance
FROM join_table
INNER JOIN
(
SELECT
slave_id,
MIN(distance) AS distance
FROM join_table
GROUP BY slave_id
) AS self_join
ON self_join.slave_id = join_table.slave_id
AND self_join.distance = join_table.distance
我的尝试出了什么问题
此查询会生成master_id
非常感谢任何帮助。
答案 0 :(得分:3)
这应该给出正确的结果:
select distinct t.master_id,
t.slave_id,
t.distance
from join_table t
inner join
(
SELECT ID, min(Distance) dist
FROM
(
SELECT master_ID ID, MIN(distance) AS Distance
FROM join_table
GROUP BY master_ID
UNION
SELECT slave_ID ID, MIN(distance) AS Distance
FROM join_table
GROUP BY slave_ID
) src
GROUP BY ID
) md
on t.distance = md.dist
and (t.master_id = md.id or t.slave_id = md.id)
答案 1 :(得分:0)
如果我说得对,我会这样做:
SELECT DISTINCT t.master_id
,t.slave_id
,t.distance
FROM your_table t
INNER JOIN
(
SELECT master_id id, min(distance) distance
FROM your_table
GROUP BY master_id
UNION
SELECT slave_id id, min(distance) distance
FROM your_table
GROUP BY slave_id
) sub
ON (sub.id = t.master_id AND sub.distance = t.distance)
OR (sub.id = t.slave_id AND sub.distance = t.distance)