mysql - 对 2 个表的查询进行计数

标签 mysql sql database count

我有两张这样的 table 。对于给定的属性(在表 doc_attribute 中)和文件中的给定“单词”(在文档中),我想找到不包含该特定属性但在文件中包含该“单词”的不同 doc_id 的计数。

例如,如果给定的属性是camera,而'word'是mobile,那么结果应该是2。(即,第2、3、5个doc_id不包含camera,其中只有第2和3个包含'word ' 文件中的移动设备)

table doc_attribute
+--------+-----------+--------+
| doc_id | attribute | value  |
+--------+-----------+--------+
|     1 | product   | mobile |
|     1 | model     | lumia  |
|     1 | camera    | 5mp    |
|     2 | product   | mobile |
|     2 | model     | lumia  |
|     2 | ram       | 1gb    |
|     3 | product   | mobile |
|     3 | year      | 2014   |
|     3 | made-in   | china  |
|     4 | brand     | apple  |
|     4 | model     | iphone |
|     4 | camera    | 5mp    |
|     5 | product   | camera |
|     5 | brand     | canon  |
|     5 | price     | 20000  |



  table document
  +--------+-----------------------------+
  | doc_id | file                        |
  +--------+-----------------------------+
  |     1 | lumia 5mp mobile 1gb   2014  |
  |     2 | lumia 8mp mobile 1gb   2015  |
  |     3 | galaxy mobile fullhd 2gb     |
  |     4 | iphone apple 5mp 2013 new    |
  |     5 | canon 20000 new dslr 12mp    |

当前查询:

select count(doc_id)
from document
where doc_id not in (select doc_id from doc_attribute
                     where attribute = 'camera')
  and file REGEXP '[[:<:]]mobile[[:>:]]';

最佳答案

正则表达式和左连接即可完成。

declare @attribute varchar(128), @word varchar(128)

SELECT @attribute='camera', @word='mobile'

SELECT count(DISTINCT document.id) Results
FROM document
LEFT JOIN doc_attribute
on document.id=doc_attribute.id AND doc_attribute.attribute=@attribute
WHERE doc_attribute.id IS NULL
AND file like '%'+@word+'%'

关于mysql - 对 2 个表的查询进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31248134/

相关文章:

mysql - 如何创建 SQL 查询来显示已读消息的计数器

sql - 在 SQL 中将负载从 VARBINARY 转换为 VARCHAR

database - 如何使用 bool 属性检查运行查询

MYSQL IN语句

jquery - 自动完成jquery和SQL,ASP.NET

python - 在 python 中连接到代理 (SOCKS) 数据库

PHP 无法正确输出特殊字符

php - 获取PHP+MySQL中的热门词

mysql - 续集专业版 : How to change a string to a date during import?

python - 使用 Flask + SqlAlchemy 只创建一个表