1

如何在 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');

在此处输入图像描述

4

3 回答 3

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
于 2013-10-09T11:51:38.660 回答
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

于 2013-10-09T11:50:50.593 回答
1

像这样的事情会做到这一点

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

试试这个小提琴

于 2013-10-09T11:55:07.077 回答