我有一张桌子:
$taxonomy_table (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` varchar(10) NOT NULL,
`title` varchar(255) NOT NULL,
`media_id` int(11) NOT NULL,
`playlist_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
INDEX `media_id` (`media_id`),
CONSTRAINT `mqap_taxonomy_ibfk_1` FOREIGN KEY (`media_id`) REFERENCES {$media_table} (`id`) ON DELETE CASCADE ON UPDATE CASCADE
)";
media_id type title
------------------------------
23 tag fashion
23 tag beauty
23 category foo
24 tag fashion
24 category foo
我要选择带有所有这些标签=“ fashion,beauty”和category =“ foo”的物品,所以只有media_id = 23。
查询为:
$query = "SELECT media_id
FROM {$taxonomy_table}
WHERE type='tag' AND title IN ($arg)
AND type='category' AND title IN ($arg2)
AND playlist_id=%d
GROUP BY media_id
HAVING count(DISTINCT title) = $total";
$ arg =“时尚,美丽”,$ arg2 =“ foo”
"SELECT media_id
FROM wp_mvp_taxonomy
WHERE type='tag'
AND title IN (%s,%s)
AND type='category'
AND title IN (%s)
GROUP BY media_id
HAVING count(DISTINCT title) = 3"
但这不返回任何内容。
答案 0 :(得分:1)
您可能想要OR
:
"SELECT media_id
FROM wp_mvp_taxonomy
WHERE (type='tag' AND title IN (%s,%s))
OR (type='category' AND title IN (%s)) -- here
GROUP BY media_id
HAVING count(DISTINCT title) = 3"
原文:
WHERE type = 'tag' ... AND type ='category' => always false
答案 1 :(得分:1)
您需要OR
,并添加括号,因为AND
具有优势。
$query = "SELECT media_id
FROM {$taxonomy_table}
WHERE playlist_id=%d
AND ( ( type='tag' AND title IN ($arg) )
OR ( type='category' AND title IN ($arg2) )
)
GROUP BY media_id
HAVING count(DISTINCT title) = $total";