left join
该
tags
表,并在join子句中包含要搜索的ID,并在中检查计数
having
。
SELECt u.id,u.name,GROUP_CONCAt(ut.tagid) as tagsFROM users u LEFT JOIN usertag as ut ON u.id = ut.userid LEFT JOIN tags t ON t.id=ut.tagid AND t.ID IN (10,20,30) --change this as neededGROUP BY u.id,u.nameHAVINg COUNT(ut.tagid) >= COUNT(t.id) AND COUNT(t.id) = 3 --change this number to the number of tags
FIND_IN_SET
如果值有限,则可以使用另一种选择。例如,
SELECt * FROM (SELECt u.*, GROUP_CONCAt(ut.tagid) as tags FROM users as u LEFT JOIN usertag as ut ON u.id = ut.userid GROUP BY u.id) TWHERe FIND_IN_SET('10',tags) > 0 AND FIND_IN_SET('20',tags) > 0