假设我有一张 table :

当前表:

title_id        title_name               title_qty
   1       A.I. Artificial Intelligence      2
   2       Batman Begins                    40
   3       2012                              7
   4       101 Dalmatians                   23
   5       Act of Valor                      1
   6       Batman                           50
   7       20 Million Miles to Earth       340

我想要一个输出:

所需的输出:
   title_id        title_name               title_qty  title_char
       4          101 Dalmatians                23          #
       7          20 Million Miles to Earth     340         #
       3                2012                    7           #
       1          A.I. Artificial Intelligence  2           A
       5          Act of Valor                  1           A
       6          Batman                        50          B
       2          Batman Begins                 40          B

根据我在Stack Overflow中阅读的内容,检查字符是否为数字的最快方法是使用LIKE'[0-9]%',因此我想到了

查询:



输出:
title_id        title_name               title_qty  title_char
   4          101 Dalmatians                23          1
   7          20 Million Miles to Earth     340         2
   3                2012                    7           2
   1          A.I. Artificial Intelligence  2           A
   5          Act of Valor                  1           A
   6          Batman                        50          B
   2          Batman Begins                 40          B

如上所示,它根本不起作用。但是,如果我将LIKE更改为匹配一位数字,则可以正常工作:


title_id        title_name               title_qty  title_char
   4          101 Dalmatians                23          #
   7          20 Million Miles to Earth     340         2
   3                2012                    7           2
   1          A.I. Artificial Intelligence  2           A
   5          Act of Valor                  1           A
   6          Batman                        50          B
   2          Batman Begins                 40          B

我最初以为它不起作用,因为我的查询有点复杂,所以我做了一个简单的SELECT WHERE。 LIKE添加在WHERE之后。

无输出(应为三个):
SELECT * FROM title WHERE title_name LIKE '[0-9]%' ORDER BY title_name

按预期工作:
SELECT * FROM title WHERE title_name LIKE '1%' ORDER BY title_name

SELECT * FROM title WHERE title_name LIKE '2%' ORDER BY title_name

根据SQL文档,



有人知道如果使用字符类[0-9]为何它不起作用?作为初学者,如果我错了,请纠正我。但是我很好奇为什么使用LIKE'1%'或任何数字,而LIKE'[0-9]%'不会给出任何结果,为什么它可以工作?文档说应该匹配任何数字对吗?如果要求将其强制转换为整数,则它不能在我的所有测试中都可以正常工作,对吗?因为在进行LIKE比较之前我没有进行转换。

SQL fiddle : http://sqlfiddle.com/#!2/492906/7

最佳答案

The documentation有点令人困惑。我希望仔细剪一下可以使它更清晰:

由于最后一句话在“其他类型的模式匹配”下,因此它仅适用于您已经找到的RLIKE,而不适用于LIKE

10-08 13:36
查看更多