我有两个表,如:
id_image id_things url_image id_type_image
1 1 photo.jpg 1
2 1 sketch.jpg 2
3 2 324532.pdf 3
4 3 345323.pdf 3
和
id_type_image description
1 photo
2 sketch
3 datasheet
我想要这个查询结果:
id_things url_image(photo) url_image(sketch)
1 photo.jpg sketch.jpg
2 NULL NULL
3 NULL NULL
我如何执行查询以获得结果?
答案 0 :(得分:0)
尝试此查询:
select
e.id_thing,
(select i.url_image from image i where i.id_thing = e.id_thing and i.id_type_image = 1) as photo,
(select i.url_image from image i where i.id_thing = e.id_thing and i.id_type_image = 2) as sketch,
(select i.url_image from image i where i.id_thing = e.id_thing and i.id_type_image = 3) as datasheet
(
select distinct
i.id_thing
from image i
) e
答案 1 :(得分:0)
解决!!结果:
select id_things, (select url_image from image ii where id_type_image = 1 and ii.id_things = i.id_things) as photo, (select url_image from image ii where id_type_image = 2 and ii.id_things = i.id_things) as sketch from image i
group by id_things
order by id_things
谢谢你@ Abihabi87你给我指路了!
答案 2 :(得分:0)
我认为Pivot会解决您的问题。
WITH table_1 AS
(SELECT 1 id_image, 1 id_things, 'photo.jpg' url_image, 1 id_type_image
FROM DUAL
UNION
SELECT 2 id_image, 1 id_things, 'sketch.jpg' url_image, 2 id_type_image
FROM DUAL
UNION
SELECT 3 id_image, 2 id_things, '324532.pdf' url_image, 3 id_type_image
FROM DUAL
UNION
SELECT 4 id_image, 3 id_things, '345323.pdf' url_image, 3 id_type_image
FROM DUAL),
table_2 AS
(SELECT 1 id_type_image, 'photo' description
FROM DUAL
UNION
SELECT 2 id_type_image, 'sketch' description
FROM DUAL
UNION
SELECT 3 id_type_image, 'datasheet' description
FROM DUAL)
SELECT *
FROM (SELECT id_things, y.description, x.url_image
FROM table_1 x JOIN table_2 y ON x.id_type_image = y.id_type_image
)
pivot (
min(url_image)
for description in
('photo' "url_image(photo)",'sketch' "url_image(sketch)"));