MySQL按关键字排序匹配
我有一张这样的桌子: mysql> select * from test; +-------------+ | name | +-------------+ | one | | two | | three | | tic tac toe | | tac toe tic | +-------------+ 5 rows in set (0.00 sec)MySQL按关键字排序匹配,sql,mysql,search,Sql,Mysql,Search,我有一张这样的桌子: mysql> select * from test; +-------------+ | name | +-------------+ | one | | two | | three | | tic tac toe | | tac toe tic | +-------------+ 5 rows in set (0.00 sec) 或者我需要instr()返回NULL而不是0。您需要按2列排序,第一列指示是否匹配(以
或者我需要instr()返回NULL而不是0。您需要按2列排序,第一列指示是否匹配(以使0位于底部) 关于使用NULL的注意事项,它们位于查询的顶部,因此将0转换为NULL不起作用
select a
from (select 1 as a union all select null) b
order by a
结果
(NULL)
1
使用
IF
可以执行您想要的操作:当不存在匹配项时,返回一个不同于零的值:
select * from test order by IF(instr(name, 'toc'), instr(name, 'toc'), 65535) desc;
如果你喜欢简洁:
select *
from test
order by
instr(name, 'tac') = 0,
instr(name, 'tac') desc;
很好,谢谢你!我以前从未在MySQL中使用过CASE语句,也没有使用过任何条件sql语句。我认为这可能比在查询后用PHP之类的工具对结果进行排序要快。谢谢你的回复。我同意cyberkiwi建议的案例陈述,但我相信你的案例陈述会很好地发挥作用。因此我猜instr(name,'tac')=0将解析为true或false,并且在升序时首先排序false?
(NULL)
1
select * from test order by IF(instr(name, 'toc'), instr(name, 'toc'), 65535) desc;
select *
from test
order by
instr(name, 'tac') = 0,
instr(name, 'tac') desc;