我有一张桌子:
CREATE TABLE IF NOT EXISTS `columns` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`section_id` int(11) NOT NULL,
`columntype` int(11) NOT NULL,
`name` varchar(128) COLLATE utf8_bin NOT NULL,
`refer_type` int(11) NOT NULL,
PRIMARY KEY (`id`));
具有以下内容:
INSERT INTO `columns` (`id`, `section_id`, `columntype`, `name`, `refer_type`) VALUES
(9, 35, 1, 'Headline1', 0),
(10, 36, 1, 'Headline2', 0),
(11, 36, 5, 'Headline3', 10),
(12, 36, 3, 'Headline4', 0),
(13, 36, 4, 'Headline5', 10);
列refer_from
包含有关必须从中提取和计算包含数据的其他列的信息。在我的webapp中更改Headline2时,应更改Headline3和Headline5的内容。我正在webapp中执行最终计算,但是我需要一个能给我一个结果的SQL,比如
id name columntype refer_type
10 Headline2 1 4, 5
11 Headline3 5 null
12 Headline4 3 null
13 Headline5 4 null
我尝试使用类似SELECT id, name, columntype, (SELECT GROUP_CONCAT(refer_type SEPARATOR "," )...
的内容,但在所有四个结果行上都给了4,5
。
提前致谢!
答案 0 :(得分:1)
如果我做对了,你可能需要这样的选择:
SELECT c.id, c.name, c.columntype, ref.reftypes
FROM columns c LEFT JOIN
(SELECT GROUP_CONCAT(columntype SEPARATOR "," ) reftypes, refer_type
FROM columns
GROUP BY refer_type) ref
ON c.id = ref.refer_type;
答案 1 :(得分:0)
这样做:
SELECT c1.id, c1.name, c1.columntype, GROUP_CONCAT(c2.columntype ORDER BY c2.columntype) AS refer_type
FROM columns AS c1
LEFT JOIN columns AS c2 ON c1.id = c2.refer_type
GROUP BY c1.id
ORDER BY c1.id
答案 2 :(得分:0)
谢谢!这两个SQL都很棒!由于简单,我选择了Bamar的答案。