我有两个表,它们以以下方式相关:
表A是大学课程的列表以及该课程的实例,例如"课程";数学课在星期二和星期四上,因此有两个"课时"。如下表所示:
表
<表类>id 名称 类型 tbody><<tr>0001 数学 课程 0002 数学(星期四) course_period 0003 数学(星期二) course_period 表类>
必须将TableB
连接到TableA
的2个副本:
SELECT b.destination destination_id,
a2.name name_course_period,
b.source source_id,
a1.name name_course
FROM TableB b
INNER JOIN TableA a1 ON a1.id = b.source
INNER JOIN TableA a2 ON a2.id = b.destination;
将表重新创建为cte,您需要从表a
开始作为您的基表。将此表连接到b
。
然后需要将连接回a
以获得目的地的name
。
with a as (
select '0001' id, 'Maths' name, 'course' type
union all select '0002', 'Maths (Thursday)','course_period'
union all select '0003', 'Maths (Tuesday)', 'course_period'
)
, b as (
select '0001' id, '0001' source, '0002' destination
union all select '0002', '0001', '0003'
)
select
b.id as destination_id
, ref.name as name_course_period
, b.source as source_id
, a.name as name_course
from a
inner join b on b.source = a.id
inner join a ref on ref.id = b.destination --join back to a for name