Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert BIT value if row has relation

I have 3 tables BusStop, BusRoute, and Stop_Route (for M-2-M relation). Some stops do not have relation (routes), and I need to update each record in BusStop table with Bit value 1 or 0, depending on whether it has relation or not. I have a query to select all stops which have no relations:

SELECT
    BusStop.StopId 
FROM
    BusStop
    LEFT OUTER JOIN BusStop_BusRoute 
    ON BusStop.StopId = BusStop_BusRoute.StopId
WHERE 
    BusStop_BusRoute.StopId IS NULL

but I don't clearly understand how to add a value based on this result. I've read about CURSOR and CASE WHEN statements, but I still can't figure out how to apply them in my case. There is a StopStatus column type of Bit where I need to insert that value.

like image 590
Aleksei Grebenschikov Avatar asked Mar 24 '26 07:03

Aleksei Grebenschikov


1 Answers

UPDATE BusStop
SET StopStatus = 
    CASE 
        WHEN BusStop_BusRoute.StopID IS NULL THEN 0 
        ELSE 1 
    END
FROM 
    BusStop
    LEFT JOIN BusStop_BusRoute 
    ON BusStop.StopId = BusStop_BusRoute.StopId
like image 163
Kofi Sarfo Avatar answered Mar 26 '26 23:03

Kofi Sarfo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!