问题:我正在尝试将以下内容优化为一个查询。
所需结果:如果两个查询都返回至少1行,则输出True或1.如果只有一个查询返回结果,则输出false或0.感谢任何帮助!
SELECT item_id
FROM `category_item`
WHERE `category_id` =39610 AND `item_id` = 31
SELECT item_id
FROM `category_item`
WHERE `category_id` =37 AND `item_id` = 31
答案 0 :(得分:4)
SELECT COUNT(DISTINCT `category_id`)
FROM `category_item`
WHERE `category_id` IN (39610,37) AND `item_id` = 31
你可以添加== 2或> 1就此而言
编辑: 只是为了澄清:
SELECT (COUNT(DISTINCT `category_id`) > 1) AS both_have
将导致返回1或0
答案 1 :(得分:2)
检查行的最简单方法是使用exists
子句,我们可以将这两个查询与and
结合使用,以确保两个查询都返回行:
select
exists (SELECT item_id
FROM `category_item`
WHERE `category_id` =39610 AND `item_id` = 31
) AND
exists (SELECT item_id
FROM `category_item`
WHERE `category_id` =37 AND `item_id` = 31
) as `both_exist`;