1

我试图从根本上解决这个问题;我希望我仍然能够在原始查询中捕捉到我想要实现的本质!

  • 可以在此处找到生成表和数据的代码。
  • SQL 风格是Microsoft SQL Server 2000(尽管我一直在 MySQL 上运行这个精简的测试用例)

原表

+-----------+----------+----------+
| 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_idslave_id

期望结果表

+-----------+----------+----------+
| 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

任何帮助将不胜感激。

4

2 回答 2

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)

请参阅带有演示的 SQL Fiddle

于 2013-02-26T03:58:15.997 回答
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)
于 2013-02-26T03:38:52.107 回答