我有2张这样的牌桌。对于给定的属性(在表doc_attribute中)和给定的'单词'在文件中(在文档中),我想查找不包含该特定属性但包含该单词'的不同doc_id的计数。在文件中。
例如,如果给出的属性是相机和'字'是移动的,那么结果应该是2.(即,第2,第3和第5 doc_id不包含摄像头,其中只有第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[[:>:]]';
答案 0 :(得分:0)
正则表达式和左连接将执行此操作。
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+'%'