[英]Self-referencing MySQL table
我有一張桌子:
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
包含必須從中提取並計算包含數據的其他列的信息。 在我的Web應用程序中更改Headline2時,應更改Headline3和Headline5的內容。 我正在Web應用程序中執行最終計算,但是我需要一個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
。
提前致謝!
如果我做對了,您可能需要以下選擇:
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;
這樣做:
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
謝謝! 兩種SQL都很棒! 因為簡單,我選擇了Bamar的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.