在一个查询中显示其所属的每个产品的所有类别

时间:2013-08-19 03:21:04

标签: mysql sql

如何在mysql中获得如下结果?

我想通过ID获取所有产品组,并显示它属于哪个类别 如何在一个sql中获取它?
enter image description here

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `a`
-- ----------------------------
DROP TABLE IF EXISTS `a`;
CREATE TABLE `a` (
  `products_id` int(11) NOT NULL,
  `products_name` varchar(255) default NULL,
  PRIMARY KEY  (`products_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of a
-- ----------------------------
INSERT INTO `a` VALUES ('1', 'hello');
INSERT INTO `a` VALUES ('2', 'world');




SET FOREIGN_KEY_CHECKS=0;

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

-- ----------------------------
-- Records of b
-- ----------------------------
INSERT INTO `b` VALUES ('1', '1');
INSERT INTO `b` VALUES ('1', '2');
INSERT INTO `b` VALUES ('2', '1');
INSERT INTO `b` VALUES ('2', '3');

2 个答案:

答案 0 :(得分:1)

这是你想要的吗?

SELECT a.products_id, a.products_name, 
GROUP_CONCAT(CONVERT(b.categories_id,CHAR(8))) as products_to_categories
FROM a,b 
WHERE a.products_id = b.products_id
GROUP BY a.products_id, a.products_name

http://www.sqlfiddle.com/#!2/39edfc/3/0

小提琴中产生的图像

enter image description here

答案 1 :(得分:1)

使用内部联接,cheer =)

有另一种方法
SELECT a.products_id, a.products_name,group_concat(b.categories_id)  
FROM a
INNER JOIN b ON a.products_id = b.products_id
group by a.products_id, a.products_name