简体   繁体   中英

Self-referencing MySQL table

I have a 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`));

with the following content:

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);

The column refer_from contains info on which other column the containing data must be pulled from and calculated with. When Headline2 is changed in my webapp, the content of Headline3 and Headline5 should be changed. I'm performing the final calculations in the webapp, but I need a SQL that will give me a result like

    id    name      columntype refer_type
    10    Headline2 1          4, 5
    11    Headline3 5          null
    12    Headline4 3          null
    13    Headline5 4          null

I've tried with something like SELECT id, name, columntype, (SELECT GROUP_CONCAT(refer_type SEPARATOR "," )... but that gave me 4,5 on all four result rows.

Thanks in advance!

If I get it right, you might need something like this select:

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;

This does it:

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

DEMO

Thanks! Both SQLs works great! I've selected Bamar's answer because of the simplicity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM