SELECT *
FROM address
WHERE name LIKE 'a%' OR name LIKE '% a%' LIMIT 10
此查询检索以开头
或中间单词 开头name
的 s 。我怎样才能从第一个检索结果
呢?a
'a%'
'% a%'
LIKE 'a%'
LIKE '% a%'
添加ORDER BY
子句,
SELECT *
FROM address
WHERE name LIKE 'a%' OR name LIKE '% a%'
ORDER BY CASE WHEN name LIKE 'a%' THEN 0 ELSE 1 END
LIMIT 10
这里是:
SELECT t1.*
FROM (
SELECT *
FROM address
WHERE name LIKE 'a%'
LIMIT 10
) t1
WHERE t1.name LIKE '% a%'
一种方法是在查询中添加 ORDER BY 子句:
ORDER BY IF(name LIKE 'a%',1,2)
像这样的东西:
SELECT *
FROM address
WHERE name LIKE 'a%' OR name LIKE '% a%'
ORDER BY IF(name LIKE 'a%',1,2)
LIMIT 10
为了避免对大型集合(即地址中的大量行)进行“使用文件排序”操作,并且如果您只想返回 10 行,通过限制要排序的行数,看起来更复杂的查询可能会执行得更好:
SELECT c.*
FROM ( SELECT a.*
FROM (
SELECT *
FROM address
WHERE name LIKE 'a%'
LIMIT 10
) a
UNION ALL
SELECT b.*
FROM address b
WHERE b.name LIKE '% a%' AND b.name NOT LIKE 'a%'
LIMIT 10
) c
ORDER BY c.name LIKE 'a%' DESC
LIMIT 10
联合查询在这里可能是有序的。根据 MySQL 文档
要使 UNION 结果中的行由每个 SELECT 一个接一个地检索到的行集组成,请在每个 SELECT 中选择一个附加列以用作排序列,并在最后一个 SELECT 之后添加一个 ORDER BY:
(SELECT 1 AS sort_col, col1a, col1b, ... FROM t1)
UNION
(SELECT 2, col2a, col2b, ... FROM t2) ORDER BY sort_col;
因此,对于您的情况,例如
(Select *, 1 as sortcol from addresses where name like 'a%')
Union
(Select *, 2 as sortcol from addresses where name like '% a%')
Order by sortcol