开发者

Mysql complex selection

开发者 https://www.devze.com 2023-02-06 19:16 出处:网络
How to select rows with exact subcats id\'s? For example i need to pick only rows which have subcat_id 2,6 or 2,4,5,7.

How to select rows with exact subcats id's? For example i need to pick only rows which have subcat_id 2,6 or 2,4,5,7.

CREATE TABLE IF NOT EXISTS `testing123` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `cat_id` int(10) DEFAULT '0',
  `subcat_id` int(10) DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=223 DEFAULT CHARSET=utf8;

REPLACE INTO `testing123` (`id`, `cat_id`, `subcat_id`) VALUES
    (170, 32, 5),
    (171, 33, 1),
    (172, 33, 7),
    (173, 34, 5),
    (175, 35, 2),
    (176, 36, 1),
    (177, 36, 2),
    (178, 36, 7),
    (179, 37, 2),
    (180, 37, 6),
    (184, 40, 2),
    (185, 40, 5),
    (186, 40, 6),
    (187, 41, 4),
    (188, 54, 2),
    (189, 54, 4),
    (190, 54, 5),
    (191, 54, 7),
    (192, 55, 6),
    (193, 56, 2),
    (194, 56, 6),
    (195, 57, 6),
    (196, 58, 1),
    (197, 59, 3),
    (198, 60, 6),
    (199, 61, 2),
    (200, 61, 6),
    (203, 63, 1),
    (204, 63, 6),
    (205, 64, 2),
    (206, 64, 6),
    (207, 65, 1),
    (208, 65, 2),
    (209, 66, 4),
    (214, 67, 1),
    (215, 67, 5),
    (开发者_开发技巧220, 70, 1),
    (221, 70, 4),
    (222, 70, 5);

If i'm using OR or IN(), it's picking all rows, that have ANY one provided subcats, but i need to have exact matches only.

Table example provided for experiments.

Help! :)


SELECT *
  FROM testing123
 WHERE cat_id IN (SELECT cat_id
                    FROM testing123
                   WHERE subcat_id IN (2, 6)
                GROUP BY cat_id
                  HAVING COUNT(*) = 2)


SELECT *
  FROM testing123
 WHERE cat_id IN (SELECT cat_id
                    FROM testing123
                   WHERE subcat_id IN (2, 4, 5, 7)
                GROUP BY cat_id
                  HAVING COUNT(*) = 4)

Note that COUNT(*) = N clause depends on how many subcats were enumerated in the IN()

0

精彩评论

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