mysql - 获取与列表(数组)中的精确值匹配的记录

标签 mysql

我有 3 个表(report、tags、report_has_tags),需要选择只提到了 tags 的记录。下面是我正在使用的查询

SELECT r.*, rt.report_id, GROUP_CONCAT(rt.tag_id) as tag_ids, GROUP_CONCAT(t.tag_name) as tag_names 
FROM report r 
LEFT JOIN report_has_tag rt ON r.id=rt.report_id 
LEFT JOIN tags t ON rt.tag_id=t.id 
WHERE r.id in (select report_id from report_has_tag where tag_id IN (1,2) group by report_id having count(1) >1 ) 
GROUP BY r.id  
LIMIT 990 OFFSET 0

此查询返回包含标签 1,2 的所有记录以及包含标签 3,4 的记录。我只需要有标签 1、2 而不是 3 或其他标签的记录。请参阅附图 https://ibb.co/Gdr6TDF

最佳答案

您只需要没有其他 tag_id 的 report_id,您可以通过以下查询实现:

SELECT r.*, rt.report_id, GROUP_CONCAT(rt.tag_id) as tag_ids, GROUP_CONCAT(t.tag_name) as tag_names 
FROM report r 
LEFT JOIN report_has_tag rt ON r.id=rt.report_id 
LEFT JOIN tags t ON rt.tag_id=t.id 
WHERE r.id in (
    select report_id from report_has_tag group by report_id having count(1) >1 and max( tag_id ) < 3
) 
GROUP BY r.id  
LIMIT 990 OFFSET;

您只需要设置最大值,以排除 tag_id 大于 2 的标签。

关于mysql - 获取与列表(数组)中的精确值匹配的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55567886/

相关文章:

php - 从查询结果中选择第一行下一秒等

mysql - ORDER BY 格式错误的日期列

mysql - MariaDB 更改表行格式不起作用

php - 对值进行分组并从数据库中获取百分比

Mysql查询,选择所有客户及其订单

php - 导入 Prestashop 产品 1.6 至 1.7 时出现问题

php - 复杂的数据库设置 : Trying to display two field values that correspond to three other specific fields

mysql - 在数据库中查找重复条目

php - 在 jQuery 数据表中显示数据库记录

php - Doctrine2 findBy ... 在哪里