我有一个包含大量单词的数据库,但是我只想选择那些字符长度等于给定数字的记录(在示例情况3中):
$query = ("SELECT * FROM $db WHERE conditions AND length = 3");
但这不起作用...有人可以向我显示正确的查询吗?
Answers:
抱歉,我不确定您在谈论哪个SQL平台:
在MySQL中:
$query = ("SELECT * FROM $db WHERE conditions AND LENGTH(col_name) = 3");
在MSSQL中
$query = ("SELECT * FROM $db WHERE conditions AND LEN(col_name) = 3");
LENGTH()(MySQL)或LEN()(MSSQL)函数将在您可以在WHERE子句中用作条件的列中返回字符串的长度。
编辑
我知道这确实很老,但是我想扩大答案,因为正如Paulo Bueno正确指出的那样,您很可能想要的是字符数而不是字节数。谢谢Paulo。
因此,对于MySQL,有CHAR_LENGTH()
。下面的示例着重之间的差LENGTH()
的CHAR_LENGTH()
:
CREATE TABLE words (
word VARCHAR(100)
) ENGINE INNODB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;
INSERT INTO words(word) VALUES('快樂'), ('happy'), ('hayır');
SELECT word, LENGTH(word) as num_bytes, CHAR_LENGTH(word) AS num_characters FROM words;
+--------+-----------+----------------+
| word | num_bytes | num_characters |
+--------+-----------+----------------+
| 快樂 | 6 | 2 |
| happy | 5 | 5 |
| hayır | 6 | 5 |
+--------+-----------+----------------+
如果要处理多字节字符,请小心。
SELECT *
FROM my_table
WHERE substr(my_field,1,5) = "abcde";