开发者

MySQL check if two conditions return at least one result

Problem: I am trying to optimize the following into one query.

Desired Result: If both queries return at least 1 row, output True or 1. If only one query returns a result, output false or 0. Any help is appreciated!

SELECT item_id
FROM  `category_item` 
WHERE  `category_id` =39610 AND `item_id` = 31

SELECT item_id 
FROM  `category_item` 
WHERE  `c开发者_如何学Goategory_id` =37 AND `item_id` = 31


SELECT COUNT(DISTINCT `category_id`) 
FROM `category_item` 
WHERE `category_id` IN (39610,37) AND `item_id` = 31

you can add == 2 or > 1 for that matter

EDIT: just to clarify:

SELECT (COUNT(DISTINCT `category_id`) > 1) AS both_have

will result in return 1 or 0


The simplest way to check for rows is to use exists clause, and we can combine the two queries with and to make sure both queries return rows:

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`;

Demo: http://www.sqlize.com/cx00raoMa7

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜