我有2张表格如下
表1 :动物(ID是主键)
ID |Animal
----------
1 |Dog
2 |Cat
3 |Fish
4 |Bird
5 |Elephant
表2 :Pet(这里的ID是Animal
表的外键)
ID | Animal | Name
----------
1 | Dog | Annie
1 | Dog | Buckie
2 | Cat | Conner
2 | Cat | Kitten
3 | Fish| Lala
我想编写一个SQL语句,在没有违反订单的情况下,只要出现特定宠物“狗”,就会附加一行“Fish”。
预期结果应为:
ID | Animal | Name
----------
1 | Dog | Annie
3 | Fish| NULL
1 | Dog | Buckie
3 | Fish| NULL
2 | Cat | Conner
2 | Cat | Kitten
3 | Fish| Lala
答案 0 :(得分:0)
我对Oracle11g
不太确定,但我认为它有ROW_NUMBER
。
您可以在原始表格中添加行号, 然后将鱼表与相应的行号联合起来。
例如
WITH Tablex AS (
SELECT ROW_NUMBER() OVER(ORDER BY ID, Name) AS ref_id, *
FROM your_table
)
SELECT ID, Animal, Name
FROM (SELECT *
FROM Tablex
UNION ALL
SELECT *
FROM
(SELECT ref_id, 3 AS ID, 'Fish' AS Animal, NULL AS Name
FROM TableX
WHERE Animal = 'Dog'
) x
) X
ORDER BY ref_id, id
如上所述,行的顺序仅取决于ORDER BY
子句,并且该顺序可能实际上并未包含在表中(如果您将其INTO
置于其中)。
答案 1 :(得分:0)
with Q as (
select ID, Animal, Name,
row_number() over (order by id, name) rnum
from Pet
)
select ID, Animal, Name, rnum
from Q
union all
select 3, 'Fish', NULL, rnum+0.5
from Q
where ID=1 and name in('Annie','Buckie')
order by rnum
答案 2 :(得分:0)
试试这个
select tn.Id
, case when tt.rn = 0 then tn.Animal else 'Fish' end Animal
, case when tt.rn = 0 then tn.Name else NULL end Name
, tn.rn+tt.rn rn
from (
select ID, Animal, Name, 2 * row_number() over (order by id, name) as rn
from pet
) tn
join (
select 0 rn from dual union
select 1 from dual
) tt on tt.rn <= case Animal when 'Dog' then 1 else 0 end
order by tn.rn+tt.rn;