SQL可以选择同一列不相似的行。
我有此表City_Names
数据库名DataPostalCode
id |AR |HB |ENG
---+----------+----------+-----------
1 |valueAR |valueHB |valueENG
---+----------+----------+-----------
2 |TamraAR |TamraHB |TamraENG
---+----------+----------+-----------
3 |TamraAR |Tamra2HB |TamraENG
---+----------+----------+-----------
4 |KabulAR |KabulHB |KabulENG
---+----------+----------+-----------
6 |KabulAR |KabulHB |KabulENG
---+----------+----------+-----------
7 |KabulAR |KabulHB |KabulENG
---+----------+----------+-----------
8 |Azor |Azor |Azor
---+----------+----------+-----------
9 |Azor |Azor |Azor
---+----------+----------+-----------
...
上面的数据只是一个演示,而不是真实的数据。
请参见id
第4行,第6行和第7行在AR + HB + ENG中具有相似的值。
行id
8和9相同。
但第id
行1是单行。
AR + ENG的id
行2和3(我正在寻找的行)相似,但HB列不相似。
因此,我正在训练编写sql代码,以选择不像这样的行,结果应该是这样。
id |AR |HB |ENG
---+----------+----------+-----------
2 |TamraAR |TamraHB |TamraENG
---+----------+----------+-----------
3 |TamraAR |Tamra2HB |TamraENG
---+----------+----------+-----------
我应该写什么?
SELECT id,AR,HB,ENG FROM City_Names ....;
答案 0 :(得分:2)
您可以使用exists
:
select cn.*
from city_names cn
where exists (select 1
from city_names cn2
where cn2.ar = cn.ar and
cn2.eng = cn.eng and
cn2.hb <> cn.hb
);
如果愿意,还可以将其减少为一行。确切的语法取决于数据库:
select cn.ar, cn.eng,
list_agg(cn.id, ',') over (order by id) as ids,
list_agg(cn.hb, ',') over (order by id) as hbs
from city_names cn
group by cn.ar, cn.eng
having min(cn.hb) <> max(cn.hb);
聚合字符串的具体功能取决于数据库。
答案 1 :(得分:1)
您可以使用exists
:
select cn.*
from City_Names cn
where exists (select 1
from City_Names cnn
where cn.AR = cnn.AR and cn.ENG = cnn.ENG and cn.HB <> cnn.HB
);
答案 2 :(得分:0)
您还可以使用LEFT JOIN
获得结果:
SELECT
T2.*
FROM
temp AS T1
LEFT JOIN temp AS T2 ON T1.AR = T2.AR AND T1.ENG = T2.ENG AND T1.HB <> T2.HB
结果:
id AR HB ENG
3 TamraAR Tamra2HB TamraENG
2 TamraAR TamraHB TamraENG