我有这样的数据库设置:
Table: Sections section_id | section_name i23kj | News o492q | Events Table: Subsections sub_section_id | section_id | sub_section_name q123l | i23kj | Washington Post z765a | i23kj | NY Times w439m | o492q | Launch Party
我想要一个页面来打印以下信息:
News Washington Post Ny Times Events Launch Party
我正在使用查询:
SELECT Sections.section_id, Sections.section_name, Subsections.sub_section_id, Subsections.sub_section_name
FROM Sections INNER JOIN Subsections
ON Sections.section_id=Subsections.section_id
但是这会返回:
News Washington Post News Ny Times Events Launch Party
如何将查询更改为仅显示一次部分和该部分下的子部分
答案 0 :(得分:1)
你需要使用子查询,只需测试它就可以看到 DEMO :
create table sections
(
section_id varchar(10),
section_name varchar(50)
);
create table subsections
(
sub_section_id varchar(10),
section_id varchar(10),
sub_section_name varchar(50)
);
insert into sections
values('i23kj','News'),
('o492q','Events');
insert into subsections
values('q123l','i23kj','Washington Post'),
('z765a','i23kj','NY Times'),
('w439m','o492q','Launch Party');
以下查询的结果正是您想要的问题:
select case
when q2.sub_section_id is null then section_name
else sub_section_name end
from
(select * from ( select Sections.section_id, Sections.section_name,
null as sub_section_id, null as sub_section_name
FROM Sections
union
SELECT Sections.section_id, Sections.section_name,
Subsections.sub_section_id, Subsections.sub_section_name
FROM Sections INNER JOIN Subsections
ON Sections.section_id=Subsections.section_id) as q
order by q.section_id,q.sub_section_id) as q2