简体   繁体   中英

How to create a check if record does not exists in mysql?

Hi I want to show the county in the following query but if county does not exist, return the city instead.

        SELECT P.id  AS id, SUM(P.price)  AS price, 
                    P.tax, 
                    county  
                FROM Purchases AS  P
                JOIN Status  AS S       ON S.id = T.status_id
                JOIN Shipping AS Ship   ON S.shipping_id= Ship.id
                JOIN Shipping_Addresses AS  SA      ON Ship.shipping_address_id = SA.id
                JOIN Zip_Codes          AS ZIP      ON ZIP.zip_code = SA.zip_code
                JOIN Counties           AS C        ON ZIP.city = C.city
                JOIN States             AS STATE    ON STATE.id = C.county_state_id

                GROUP BY ZIP.zip_code
                ORDER BY county

Thanks

Try using COALESCE() :

COALESCE(county, city) AS location

If county is NULL it will return the value of city instead.

So:

SELECT P.id  AS id, SUM(P.price)  AS price, 
    P.tax, 
    COALESCE(county, city) AS location

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