求助:如下三个表(内,外,左,右) 连接的SQL 语句怎么写呢?
有三张表
表 A (字段 a_id) ,数据 {1,2,3,4}
表B (字段 b_id) ,数据 {7,8 ,9}
表C (字段 b_id,b_id,c_id) 数据 {(1,7,1),(3,8,2))}
要求根据 a_id="1" 查询出这样的结果:
a_id b_id c_id
1 7 1
1 8
1 9
我用的 右连接 去操作
select a.a_id , b.b_id ,c.c_id from C c right join B b on (c.b_id=b.b_id) right join A a on
(c.a_id=a.a_id) 这样的搜索结果当然只能有第一条数据 ,B里面为 8 ,9 的信息就不可以了。
请问 该如何改呢 ?
------解决方案--------------------WITH A AS
(
SELECT 1 A_ID FROM DUAL
UNION
SELECT 4 A_ID FROM DUAL
UNION
SELECT 3 A_ID FROM DUAL
UNION
SELECT 2 A_ID FROM DUAL),
B AS
(SELECT 7 B_ID FROM DUAL
UNION
SELECT 8 B_ID FROM DUAL
UNION
SELECT 9 B_ID FROM DUAL),
C AS
(SELECT 1 A_ID,7 B_ID,1 C_ID FROM DUAL
UNION
SELECT 3 A_ID,8 B_ID,2 C_ID FROM DUAL)
SELECT A.A_ID,B.B_ID,C.C_ID
FROM A CROSS JOIN B
LEFT JOIN C
ON A.A_ID=C.A_ID AND B.B_ID=C.B_ID
WHERE A.A_ID=1
1 1 7 1
2 1 8
3 1 9
------解决方案--------------------select a.a_id , b.b_id ,c.c_id from A a,B b,C c
where a.a_id=c.a_id and b.b_id=c.b_id
还有个 left join 也可以
select a.a_id , b.b_id ,c.c_id from A a
left join C c on c.a_id = a.a_id
left join B b on b.b_id = c.b_id