这将做:
SELECT nr, Name FROM (
SELECT nr, Name, (
SELECT MIN(nr) FROM _table_ AS _ WHERE Name=_table_.Name
) AS _min FROM _table_
) ORDER BY _min, nr
在http://sqlfiddle.com/#!7/674bf/5检查它。
编辑:如果_table_
实际上是表的联合,则有 3 个选项:
1)创建一个视图,所以查询仍然有效:
CREATE VIEW _table_ AS SELECT * FROM _table1_ UNION ALL SELECT * FROM _table2_
2)_table_
用表联合替换先前的查询:
SELECT nr, Name FROM (
SELECT nr, Name, (
SELECT MIN(nr) FROM (
SELECT * FROM _table1_ UNION ALL SELECT * FROM _table2_
) AS _ WHERE Name=_table_.Name
) AS _min FROM (
SELECT * FROM _table1_ UNION ALL SELECT * FROM _table2_
) AS _table_
) ORDER BY _min, nr
3)也许有一些优化(我说也许!):
SELECT _un.* FROM (
SELECT * FROM _table1_
UNION ALL
SELECT * FROM _table2_
) AS _un
JOIN (
SELECT Name, MIN(nr) AS _min FROM (
SELECT * FROM _table1_
UNION ALL
SELECT * FROM _table2_
) GROUP BY Name
) AS _min ON _un.Name=_min.Name
ORDER BY _min, _un.nr