Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL按关键字排序匹配_Sql_Mysql_Search - Fatal编程技术网

MySQL按关键字排序匹配

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列排序,第一列指示是否匹配(以

我有一张这样的桌子:

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列排序,第一列指示是否匹配(以使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;