SELECT *
   FROM address 
   WHERE name LIKE 'a%' OR name LIKE '% a%' LIMIT 10

该查询检索name s表示与开始a无论是在开始'a%'
或换句话说,中间是'% a%' 我如何首先从LIKE 'a%'检索结果
然后按LIKE '% a%' ?。

===============>>#1 票数:3 已采纳

添加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

===============>>#2 票数:0

这里是:

SELECT t1.*
FROM (
   SELECT *
   FROM address 
   WHERE name LIKE 'a%'
   LIMIT 10
) t1
WHERE t1.name LIKE '% a%' 

===============>>#3 票数:0

一种方法是在查询中添加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

===============>>#4 票数:0

此处可以进行联合查询。 根据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

链接: http//dev.mysql.com/doc/refman/5.0/en/union.html

  ask by Sami Al-Subhi translate from so

未解决问题?本站智能推荐: