
[英]Retrieving data from two tables at once with one table referencing the other
[英]Two LIKE conditions but retrieving from one first then the other
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.