如何获得与另一个给定类别共享至少一个产品的类别?

时间:2013-10-09 11:40:52

标签: mysql

如何在sql中获取与至少一个产品共享另一个给定类别的类别?

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `p2c`
-- ----------------------------
DROP TABLE IF EXISTS `p2c`;
CREATE TABLE `p2c` (
  `products_id` int(11) NOT NULL default '0',
  `categories_id` int(11) NOT NULL default '0',
  PRIMARY KEY  (`products_id`,`categories_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of p2c
-- ----------------------------
INSERT INTO `p2c` VALUES ('1001', '1');
INSERT INTO `p2c` VALUES ('1001', '2');
INSERT INTO `p2c` VALUES ('1002', '1');
INSERT INTO `p2c` VALUES ('1003', '2');
INSERT INTO `p2c` VALUES ('1004', '1');
INSERT INTO `p2c` VALUES ('1004', '2');
INSERT INTO `p2c` VALUES ('1005', '3');
INSERT INTO `p2c` VALUES ('1006', '2');
INSERT INTO `p2c` VALUES ('1006', '3');
INSERT INTO `p2c` VALUES ('1007', '4');

enter image description here

3 个答案:

答案 0 :(得分:3)

 select distinct a.categories_id as categories_associated_with_1
    from p2c as a
    inner join (select products_id
    from p2c
    where categories_id=1) as b
    on a.products_id=b.products_id
where a.categories_id<>1

答案 1 :(得分:2)

类似的东西:

您在同一个表上进行内部联接。 products_id必须相同,categories_id必须不同。

select distinct p2.categories_id
from p2c p1
inner join p2c p2 
    on p1.products_id = p2.products_id and 
       p1.categories_id <> p2.categories_id
where p1.categories_id = 1

SqlFiddle

答案 2 :(得分:1)

像这样的东西会这样做

SELECT
    DISTINCT categories_id
  FROM p2c
  WHERE
    categories_id != 1
    AND products_id IN
      (SELECT products_id FROM p2c WHERE categories_id = 1)

试用this fiddle