我有两张这样的桌子

Cities:
id__| country__
--------------
_1__| 1000
_2__| 1001
_3__| 1002

Translates:
id__ | city_id  |      name       | __lang__ | _order_
-------------------------------------------------------
1____|     1    | Dnipro          | en       | 2
2____|     1    | Dnipropetrovsk  | en       | 1
3____|     1    | Ekaterinoslav   | en       | 3

如何只加入城市id上的按顺序翻译的第一个城市id?
我想要下一个结果:
id__| country__ | city_id  |      name       | __lang__ | _order_
1   | 1000      |    1     |  Dnipropetrovsk |   en     |    1

我试过这样的密码
SELECT * FROM `cities`
INNER JOIN `translates` ON `cities`.`id` = `translates`.`city_id`
ORDER BY `order`
GROUP BY `city_id`

但是GROUPBY忽略ORDERBY,并且无论是否有ORDERBY,左始终是同一行

最佳答案

有很多方法可以做到这一点,但这里有一种方法!
SELECT cities.*, translates.*FROM citiesINNER JOIN translatesON translates.city_id = cities.idINNER JOIN( SELECT city_id, MIN(order) as order FROM translates GROUP BY city_id) relevant_translatesON relevant_translates.city_id = translates.city_idAND relevant_translates.order = translates.order;
relevant_translates子查询获取转换表中每个城市id值的最小顺序值。然后通过使用translate进行内部连接,只保留最小顺序值的translate值。祝你好运!

10-05 19:53