2013-08-19 17 views
1

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

回答

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

+0

为什么结果products_to_categories显示(BLOB) –

+0

确定我收到了问题,现在编辑我的答案 – skv

+0

SELECT a.products_id,a.products_name, group_concat(conv(oct(b.categories_id),8,10))as a products_to_categories from a,b where a.products_id = b.products_id group by a.products_id,a.products_name –

1

存在由使用内的替代方式加入,欢呼=)

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 
相关问题