我正在尝试使用表中的多个 Like 语句在列中搜索特定匹配项,但该搜索应来自特定列。
尝试为 PHP 执行此 MySQL 语句
SELECT count(*) FROM morefiles where file like '%.doc%' or file like '%.pdf%' or file like '%.txt%' AND assignto=882
TABLE
-------
id | ProductId | file
0 882 myfile.pdf
1 831 thisfile.docx
2 232 files.mp3
3 882 otherfile.pdf
4 882 textfile.doc
我得到的结果
TABLE
-------
id | ProductId | file
0 882 myfile.pdf
1 831 thisfile.docx
3 882 otherfile.pdf
4 882 textfile.doc
我期待的结果
TABLE
-------
id | ProductId | file
0 882 myfile.pdf
3 882 otherfile.pdf
4 882 textfile.doc
表示我想搜索以仅显示 882 的产品 ID,而不是其他产品
大括号应该可以解决您的问题。
SELECT count(*) FROM morefiles
where assignto=882
and (file like '%.doc%' or file like '%.pdf%' or file like '%.txt%');
在这种情况下,我将使用函数substring_index()
来避免所有这些OR
s(否则需要将其括在括号中,因为它们的优先级低于AND
(:
select * from tablename
where productid = '882'
and substring_index(file, '.', -1) in ('doc', 'pdf', 'txt')
substring_index()
-1
作为最后一个参数返回最后一个点之后的字符串部分。
请参阅演示。
结果:
| id | ProductId | file |
| --- | --------- | ------------- |
| 0 | 882 | myfile.pdf |
| 3 | 882 | otherfile.pdf |
| 4 | 882 | textfile.doc |
如果只需要计算以下条件下的文件数:
select sum(
productid = '882'
and
substring_index(file, '.', -1) in ('doc', 'pdf', 'txt')
) as counter
from tablename
请参阅演示。
结果:
| counter |
| ------- |
| 3 |
这将起作用:
SELECT count(*)
FROM morefiles
WHERE file LIKE '%.doc'
OR file LIKE '%.pdf%'
OR file like '%.txt%'
AND assignto=882;