我正在尝试根据此处的某些条件来获取行。我想要的是获取行(如果符合条件的行可用),如果不匹配,则返回所有行。
下面是我的查询。
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
第3行出现语法错误
答案 0 :(得分:0)
您可以使用mariadb if-then-else
语句
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;
答案 1 :(得分:0)
您可以使用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
) ;
您也可以只使用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