简体   繁体   中英

MySQL Many-to-many relation - Change OR SELECT into AND

I have following code

SELECT DISTINCT t.`id_task` FROM crm_task t LEFT JOIN crm_task_tagtogroup asso USING (`id_task`) WHERE asso.id_tag IN(1,2,5,6)

My problem is that it includes on OR basis not AND basis (Excldude works fine). Lookin for efficent way to change id_task IN () to AND .
So i recieve all entries that have 1,2,5 and 6 tag assigned

Database Structure:



CREATE TABLE `crm_task_tagtogroup` (
`id_task`  INT UNSIGNED  , 
`id_tag`  INT UNSIGNED  , 
 UNIQUE KEY (`id_task`, `id_tag`)
) CHARACTER SET utf8 COLLATE utf8_general_ci ;

CREATE TABLE `crm_task` (
`id_task`  INT UNSIGNED   AUTO_INCREMENT PRIMARY KEY , 
`name`  VARCHAR(30), 
`description`  TEXT , 
`priority`  INT UNSIGNED  , 
`client_id`  INT UNSIGNED  , 
`value_netto`  INT UNSIGNED
) CHARACTER SET utf8 COLLATE utf8_general_ci ;


Any Ideas? Would like to keep it simple and not include foreach checking in PHP script

I think the code you are looking to get is close to this:

SELECT DISTINCT t.`id_task` FROM crm_task t INNER JOIN crm_task_tagtogroup tag ON (id_tag in (1,2,3)) having count(distinct id_tag) = 3;

place your list of parameters within the on clause and the count of these parameters at the end of the having count statement.

This will mean that only results that match the number of parameters are returned.

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM