SQL单查询问题

时间:2012-02-10 15:13:27

标签: sql

我需要从图像查找表中获取四个图像的图像名称。这通常不是问题,但是所有四个图像id都存储在数据库表的同一行中。表结构如下:

ITEMS_TBL
itemId
photo1
photo2
photo3
photo4 
etc

IMAGES_TBL
id
title

每个照片列代表id表格中的images_tbl

是否可以从s

获取所有图像标题

5 个答案:

答案 0 :(得分:3)

只要性能不是顶级镜头,下面的查询就可以解决问题。否则,请规范化您的数据库架构。

select
  i.itemId,
  i.photo1,
  (select title from IMAGES_TBL where id = i.photo1) as photo1_title,
  i.photo2,
  (select title from IMAGES_TBL where id = i.photo2) as photo2_title,
  i.photo3,
  (select title from IMAGES_TBL where id = i.photo3) as photo3_title,
  i.photo4,
  (select title from IMAGES_TBL where id = i.photo4) as photo4_title,
  i.etc
from ITEMS_TBL i

答案 1 :(得分:1)

在您重新设计数据库之前,创建一个视图,将该表显示为您应该具有的链接表

CREATE VIEW ItemPhotos AS

select 
  i.itemId, 
  i.photo1 as photo,
  1 as position
from ITEMS_TBL i 

UNION ALL

select 
  i.itemId, 
  i.photo2 as photo,
  2 as position
from ITEMS_TBL i 

UNION ALL

select 
  i.itemId, 
  i.photo3 as photo,
  3 as position
from ITEMS_TBL i 

UNION ALL

select 
  i.itemId, 
  i.photo4 as photo,
  4 as position
from ITEMS_TBL i 

这将给出一个观点:

itemId, photo1, photo2, photo3, photo4
1       123     124     125     126
2       223     224     225     226

这样:

itemId, photo, position
1       123    1
1       124    2
1       125    3
1       126    4
2       223    1
2       224    2
2       225    3
2       226    4

从中加入其他表格更容易。

答案 2 :(得分:0)

尝试这样的事情:

select img_photo1.title as photo1,
   img_photo2.title as photo2,
   img_photo3.title as photo3,
   img_photo4.title as photo4,
from
ITEMS_TBL items,
IMAGES_TBL img_photo1,
IMAGES_TBL img_photo2,
IMAGES_TBL img_photo3,
IMAGES_TBL img_photo4
where 
img_photo1.id = items.photo1
AND img_photo2.id = items.photo2
AND img_photo3.id = items.photo3
AND img_photo4.id = items.photo4

答案 3 :(得分:0)

这个怎么样?

select P.itemId,I1.Title,I2.Title,I3.Title,I4.Title
from ITems_tbl P 
left join IMAGES_TBL I1 on P.Photo1= I1.ID
left join IMAGES_TBL I2 on P.Photo2= I2.ID
left join IMAGES_TBL I3 on P.Photo3= I3.ID
left join IMAGES_TBL I4 on P.Photo4= I4.ID

答案 4 :(得分:0)

select
i.itemId,
i.photo1,
i.photo2, 
i.photo3,
i.photo4,
MAX(CASE WHEN a.id = i.photo1 THEN a.title END) AS photo1_title,
MAX(CASE WHEN a.id = i.photo2 THEN a.title END) AS photo2_title,
MAX(CASE WHEN a.id = i.photo3 THEN a.title END) AS photo3_title,
MAX(CASE WHEN a.id = i.photo4 THEN a.title END) AS photo4_title

FROM ITEMS_TBL i
LEFT JOIN IMAGES_TBL a ON (a.id = i.photo1 OR a.id=i.photo2 OR a.id=i.photo3  
  OR a.id=i.photo4)
GROUP BY i.itemId,i.photo1,
i.photo2, 
i.photo3,
i.photo4

对于mysql来说,仅仅GROUP BY i.itemID

就足够了