我有一张桌子
表1
| ID | Description | Type |
| 1 | Desc 1 | type1 |
| 2 | Desc 2 | type1 |
| 3 | Desc 11 | type1 |
| 4 | Desc 21 | type1 |
| 5 | Desc 12 | type1 |
| 6 | Desc 31 | type1 |
| 7 | Desc 3 | type1 |
| 8 | Desc 111 | type1 |
| 9 | Desc 112 | type1 |
relationtable1
table1.id< - > relationtable1.rel_to_id和table1.id< - > relationtable1.rel_from_id
| ID | rel_to_id | rel_from_id | relation |
| 1 | 3 | 1 | parent |
| 2 | 4 | 2 | parent |
| 3 | 5 | 1 | parent |
| 4 | 6 | 7 | parent |
| 5 | 8 | 3 | parent |
| 6 | 9 | 3 | parent |
请帮我一个mysql查询,它会让我产生 预期成果:
| ID | Description | Type |
| 1 | Desc 1 | type1 |
| 3 | Desc 11 | type1 |
| 8 | Desc 111 | type1 |
| 9 | Desc 112 | type1 |
| 5 | Desc 12 | type1 |
| 2 | Desc 2 | type1 |
| 4 | Desc 21 | type1 |
| 7 | Desc 3 | type1 |
| 6 | Desc 31 | type1 |
答案 0 :(得分:0)
不幸的是,您提供的关系表(issuerelationtable)不是用于生成相邻列表的有效Clousure表。这是它应该如何存储引用..
CREATE TABLE `issuerelationtable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`rel_to_id` int(11) DEFAULT NULL,
`rel_from_id` int(11) DEFAULT NULL,
`relation` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=18 ;
INSERT INTO `issuerelationtable` (`id`, `rel_to_id`, `rel_from_id`, `relation`) VALUES
(1, 1, 1, NULL),
(2, 3, 1, NULL),
(3, 5, 1, NULL),
(4, 8, 1, NULL),
(5, 9, 1, NULL),
(6, 2, 2, NULL),
(7, 4, 2, NULL),
(8, 4, 4, NULL),
(9, 3, 3, NULL),
(10, 8, 3, NULL),
(11, 9, 3, NULL),
(12, 5, 5, NULL),
(13, 6, 6, NULL),
(14, 7, 7, NULL),
(15, 6, 7, NULL),
(16, 8, 8, NULL),
(17, 9, 9, NULL);
要获得所需的输出,查询应为..
SELECT
DISTINCT(it.id),
it.description,
it.type
FROM
issuetable it
INNER JOIN issuerelationtable irt ON it.id=irt.rel_from_id
WHERE
irt.rel_to_id IN (SELECT id FROM issuetable)
ORDER BY
it.description
希望它有所帮助。