gpt4 book ai didi

带有两个表连接的mysql查询

转载 作者:行者123 更新时间:2023-11-30 01:15:07 26 4
gpt4 key购买 nike

各位

我有 2 个表国家/地区代码,cctonumbers,如下所述。

我尝试了查询,但没有得到所需的输出。

我的输出

 country          destination                     country_code   destination_code

Afghanistan Afghanistan Mobile Etisalat 93 78
Afghanistan Afghanistan Mobile Etisalat 93 72
Afghanistan Afghanistan Mobile Roshan 93 79
Afghanistan Afghanistan 93 93

所需输出

country          destination                     country_code   destination_code

Afghanistan Afghanistan Mobile Etisalat 93 78

Afghanistan Afghanistan Mobile Etisalat 93 72

Afghanistan Afghanistan Mobile Roshan 93 79

使用的表格如下

国家/地区代码表

id       parentid   countryname 
1031 0 afghanistan
1035 1031 Afghanistan Mobile Etisalat
1036 1031 Afghanistan Mobile Roshan

cctonumbers 表

id       countrycode_id     parentid         number 
15731 1031 0 93
15197 1035 15731 78
15198 1035 15731 72
15199 1036 15731 79

我使用的查询如下,但没有得到想要的结果。

select * 
from
cctonumbers
LEFT JOIN countrycodes as CC
ON cctonumbers.countrycode_id = CC.id
WHERE
( CC.parentid=0
AND number like '93%'
and cctonumbers.id in
( select cctonumbers.parentid
from cctonumbers
LEFT JOIN countrycodes as CC
ON cctonumbers.countrycode_id = CC.id
WHERE number like '7%'
AND CC.parentid!=0 )
)
or ( CC.parentid != 0
AND number like '7%'
AND CC.parentid in
( select CC.id
from cctonumbers
LEFT JOIN countrycodes as CC
ON cctonumbers.countrycode_id=CC.id
WHERE CC.parentid=0
AND number like '93%' )
)
ORDER BY
cctonumbers.number Asc

最佳答案

您似乎正在寻找与特定国家/地区代码关联的所有目的地。由于您实际上没有显示 cctonumbers.id = 15731 的任何返回结果,因此我认为您正在旋转以获得结果。让我们反转树而不是沿着树走下去。

仅从具有父 ID 的 CCToNumbers 记录开始,因为看起来您只有 1 层深度。一旦您拥有这些子级条目,请连接回其父级上的 CCToNumbers...然后分别转到这两个条目的国家/地区代码表。

SELECT
CtoN.ID,
PCountry.CountryName,
DCountry.CountryName as Destination,
CtoNParent.Number as Country_Code,
CtoN.Number as Destination_Code
from
cctonumbers CtoN
JOIN cctonumbers as CtoNParent
ON CtoN.parentid = CtoNParent.ID
AND CtoNParent.number like '93%'
JOIN countrycodes as PCountry
ON CtoNParent.CountryCode_Id = PCountry.ID
JOIN countrycodes as DCountry
ON CtoN.CountryCode_Id = DCountry.ID
where
CtoN.number like '7%'

关于带有两个表连接的mysql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19137523/

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