简体   繁体   中英

SQL If condition

I have a table called Train with this sample data:

train_id strt_stn_id  end_stn_id    direction
---------------------------------------------
1         1             10            D         
2         1             21            D         
3        10             1             U         
4         1             5             D         
5         1            15             D   

and a Station table with this data:

stn_id    stn_name
---------------------
1         Churchgate
2         Marine Lines
3         Charni Road
4         Grant Road
5         Mumbai Central
6         Mahalaxmi
7         Lower Parel
8         Elphinstone Road
9         Dadar
10        Matunga Road
11        Mahim
12        Bandra
13        Khar Road
14        Santacruz
15        Vile Parle  

I want station name depending on the condition. If strt_stn_id > end_stn_id , I want station name of end_stn_id else station name of strt_stn_id .

So how to use if condition in a SQL query?

Try this:

SELECT T.*, S.stn_name
FROM Train T
INNER JOIN Station S
    ON  CASE WHEN T.strt_stn_id > T.end_stn_id 
        THEN T.end_stn_id ELSE T.strt_stn_id END = S.stn_id

use case

http://www.tizag.com/sqlTutorial/sqlcase.php

gives an example of how to use

'station' = CASE
    WHEN (strt_stn_id > end_stn_id) THEN (end_stn_id)
    ELSE (strt_stn_id)
        END

Although you can definitely put the logic in the on clause, I much prefer to do two separate joins and put the logic in the select clause:

SELECT T.*,
       (case when t.strt_stn_id > t.end_stn_id then starts.stn_name
             else ends.stn_name
        end) as TheName
FROM Train T INNER JOIN
     Station Starts
     ON T.strt_stn_id = Starts.stn_id inner join
     Station ends
     on T.end_stn_id = ends.stn_id

In general, a case statement or function all in an on clause prevents the engine from using indexes. If the tables have reasonable indexes (such as on their primary keys), this version will work better. As an aside, I also think having the logic in the select clause is more understandable, but I recognize that others might disagree.

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