简体   繁体   中英

Conditionally sql query

I have this simple query

select * from users where name = 'User1'

I'd like to extend the query's functionality whatever the query returns 0 records the query will fetch the data by other clause.

where name = 'Default'

If the first clause will fetch some records the second clause will be ignored.

EDIT

Oracle

SELECT * FROM users WHERE name = 'User1'
UNION ALL 
SELECT * FROM users WHERE name = 'Default' 
    AND NOT EXISTS (SELECT 1 FROM users WHERE name='User1')
 IF EXISTS (SELECT * from users where name = 'User1')
   SELECT * from users where name = 'User1';
 ELSE
   SELECT * from users where name = 'Default';
select top 1 * from users where name in ('User1', 'Default') order by name desc

:P

WITH T AS   (
        SELECT  users.*,
        RANK() OVER (ORDER BY CASE WHEN name = 'User1' THEN 0 ELSE 1 END) AS RN
        FROM    users
        WHERE   name IN ( 'Default','User1')
        )
SELECT * FROM T
WHERE   RN = 1

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