如何选择和排序以LIKE 'a%
开头的所有结果,然后包含LIKE '%a%'
的限制,例如3。
例如以下数据集:b,aab,baa,cad,ccc,bb,ac。 期望的结果是得到aab,ac,baa。 (如果限制为2,则不应返回包含项目。)
答案 0 :(得分:0)
在您的具体案例中,这有效:
SELECT Column1
FROM table1
WHERE (Column1 LIKE 'a%' OR Column1 LIKE '%a%')
ORDER BY Column1
LIMIT 3
以下情况应该有效,请将table1
和Column1
替换为真实姓名,然后尝试Limit 2
和Limit 3
。
当a
也可以yourcustomstring
时,此案例非常有用:
SELECT Column1
FROM (
SELECT Column1
FROM table1
WHERE Column1 LIKE 'a%'
ORDER BY Column1
) T1
UNION
SELECT Column1 FROM
(
SELECT Column1
FROM table1
WHERE Column1 LIKE '%a%'
ORDER BY Column1
) T2
LIMIT 3
工作示例:
SELECT *
FROM (
SELECT YourTableAsUnion.Column1
FROM (SELECT 'b' AS Column1
UNION
SELECT 'aab'
UNION
SELECT 'baa'
UNION
SELECT 'cad'
UNION
SELECT 'ccc'
UNION
SELECT 'bb'
UNION
SELECT 'ac'
) YourTableAsUnion
WHERE YourTableAsUnion.Column1 LIKE 'a%'
ORDER BY YourTableAsUnion.Column1
) T1
UNION SELECT * FROM (
SELECT YourTableAsUnion.Column1
FROM (SELECT 'b' AS Column1
UNION
SELECT 'aab'
UNION
SELECT 'baa'
UNION
SELECT 'cad'
UNION
SELECT 'ccc'
UNION
SELECT 'bb'
UNION
SELECT 'ac'
) YourTableAsUnion
WHERE YourTableAsUnion.Column1 LIKE '%a%'
ORDER BY YourTableAsUnion.Column1
) T2
LIMIT 3