I am trying to fetch rows based on some criteria here. What I want is to get the rows if the rows available with matching criteria AND if does not match then return all rows.
Below is my query.
SELECT t.* FROM
CASE
WHEN (SELECT COUNT(*) FROM users WHERE user_name LIKE '%10%' > 0)
// Line 3
THEN
(SELECT * FROM users WHERE user_name LIKE '%10%' LIMIT 0,10)t
ELSE
(SELECT * FROM users LIMIT 0,10)t
END
I am getting syntax error at line 3
you can use mariadb if-then-else
statement
IF (SELECT COUNT(*) FROM users WHERE user_name LIKE '%10%') > 0
SELECT * FROM users WHERE user_name LIKE '%10%' LIMIT 0,10
ELSE
SELECT * FROM users WHERE user_name
END IF;
You can use UNION ALL
:
(SELECT u.*
FROM users u
WHERE u.user_name LIKE '%10%'
LIMIT 0, 10
) UNION ALL
(SELECT u.*
FROM users u
WHERE NOT EXISTS (SELECT 1 FROM users u2 WHERE u2.user_name LIKE '%10%')
LIMIT 0, 10
) ;
You can also just use OR
:
SELECT u.*
FROM users u
WHERE u.user_name LIKE '%10%' OR
NOT EXISTS (SELECT 1 FROM users u2 WHERE u2.user_name LIKE '%10%')
LIMIT 0, 10
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.