[英]mysql query with two table joins
Folks 民间
I have 2 tables countrycodes,cctonumbers as described below. 我有2个表格国家/地区代码,cctonumbers如下所述。
I have the query that i tried but not getting the desired output. 我有我尝试过但未获得所需输出的查询。
My Output 我的输出
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
Desired output 所需的输出
country destination country_code destination_code
Afghanistan Afghanistan Mobile Etisalat 93 78
Afghanistan Afghanistan Mobile Etisalat 93 72
Afghanistan Afghanistan Mobile Roshan 93 79
The tables used are as below 使用的表格如下
countrycodes table 国家代码表
id parentid countryname
1031 0 afghanistan
1035 1031 Afghanistan Mobile Etisalat
1036 1031 Afghanistan Mobile Roshan
cctonumbers table cctonumbers表
id countrycode_id parentid number
15731 1031 0 93
15197 1035 15731 78
15198 1035 15731 72
15199 1036 15731 79
The query that im using is as below but not getting desired result. 我正在使用的查询如下,但没有得到想要的结果。
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
What you appear to be looking for is all destinations associated with a specific country code. 您似乎要查找的是与特定国家/地区代码关联的所有目的地。 Since you not actually showing any return results for your cctonumbers.id = 15731, I think you were spinning to get your results.
由于您实际上并未显示cctonumbers.id = 15731的任何返回结果,因此我认为您正在努力获取结果。 Let's reverse the tree instead of walking down it.
让我们倒下这棵树,而不是走下去。
Start with only those CCToNumbers records that have a parent ID as it appears you are only 1-level deep. 仅从看起来具有父级ID的那些CCToNumbers记录开始,您只有1级深度。 Once you have those child-level entries, join back to CCToNumbers on its parent... then go to the country codes tables for both respectively.
一旦有了这些子级别的条目,请重新加入其父级的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%'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.