Sam
Sam

Reputation: 2761

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

Upvotes: 0

Views: 55

Answers (1)

John Conde
John Conde

Reputation: 219924

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

Upvotes: 2

Related Questions