gpt4 book ai didi

mysql - 同一表中的 SQL 嵌套组

转载 作者:行者123 更新时间:2023-11-29 14:26:02 24 4
gpt4 key购买 nike

我的数据看起来像这样:

id      key         value
--------------------------------
1 country us
1 state nj
1 city trenton
2 country us
2 state nj
2 city springfield
3 country us
3 state nj
3 city belmar
4 country us
4 state ny
4 city new york
4 country us
4 state ny
4 city white plains
4 country canada
4 state ontario
4 city toronto
5 country us
5 state nj
5 city trenton

我正在尝试编写一个 SQL 查询以按独特的国家、州、城市进行分组

country     state       city
--------------------------------------
us nj trenton
us nj springfield
us nj belmar
us ny new york
us ny white plains
canada ontario toronto

我能够获得不同的国家、州和城市,但我不确定如何将它们与 ID 列连接在一起。

最佳答案

值得郑重声明的是,这是一个数据困惑,需要“规范化”。话虽如此,您可以尝试:

    SELECT cn.value as country, st.value as state, ct.value as city
FROM table cn
LEFT JOIN table st ON cn.id = st.id
LEFT JOIN table st ON cn.id = ct.id
WHERE cn.key = 'country'
AND st.key = 'state'
AND ct.key = 'city'
ORDER BY cn.value , st.value , ct.value

关于mysql - 同一表中的 SQL 嵌套组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57846443/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com