简体   繁体   中英

sql query for fetching result

I have a two tables 1) countrycodes:

在此处输入图片说明

2) cctonumbers :

在此处输入图片说明

ISSUE

When I execute the query as below :

SELECT * 
FROM   CCTONUMBERS 
       LEFT JOIN COUNTRYCODES AS CC 
              ON CCTONUMBERS.COUNTRYCODE_ID = CC.ID 
WHERE  ( CC.PARENTID = 0 
         AND NUMBER LIKE "93%" ) 
        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 
LIMIT  0, 20 

The result I get is as below

在此处输入图片说明

The result that I'm looking for is when I search for 7 in dial code i should get only the dial codes( please refer to number column in cctonumbers) starting with 7, but I'm getting "93" in the dial codes column as per the screenshot as well which is not right.

Please let me know if there is an issue in the above sql query. and please refer to the tables screenshots above for the table detail

You have used OR with

(CC.parentid=0 AND number like "93%" ) or (CC.parentid!=0 AND number like "7%" AND...

which suggests if there are any numbers with 93.. value than they would be fetched too with the query

Last row of cctonumbers table satisfies this condition where parentid is 0 and number is 93.

you are explicitely asking for countries with number 93 in the first part of your where clause (the part before the OR). This is why you get Afghanistan with dial code 93.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM