mysql在多个列中选择不同的值

x6yk4ghg  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(358)

我有一张table:

$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\u 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"

但这不是回报。

3wabscal

3wabscal1#

你需要 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";
jdg4fx2g

jdg4fx2g2#

你可能想要 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

相关问题