带有一个或多个图像的selecta图库

时间:2012-04-09 19:39:59

标签: sql

我的SQL语句有问题。我有实体Gallery属于一个类别(实体)。然后我有实体GalleryImages,并存储特定图库的图像。图库可以包含大量图像,但图库也可以不存在图像(尚未添加图像)。

现在我想构建SQL查询来选择(DESC)Gallery,它有一个或多个图像并且属于某个类别。

类别(id,名称)

图库(id,name,category_id)

GalleryImages(id,gallery_id,path)

类别 - >画廊(一对多) 图库 - > GalleryImages(一对多)

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT *
FROM Gallery as G
WHERE 
    G.category_id = 1
    AND G.id in (SELECT gallery_id FROM GalleryImages )

将1替换为您要选择的caregory_id。

答案 1 :(得分:0)

嗯 - 看起来已经回答了基本问题。但你的设置有点让我感到烦恼...... 我想我会稍微调整你的表格(假设国际化不是问题)。除此之外,我觉得“类别”和“画廊”的概念之间没有根本区别。现在,可能有“超级”和“次级”类别/画廊,图像可能同时属于多个(即,来自Renniasance,Michaelangelo,雕塑等)。它与标签的概念类似。

我可能会将你的表修改为:

Gallery (or Category, if you prefer)
=============
id  -- autoincrement
name  -- varchar(50) or something, unique
parent  -- fk reference to another Gallery.id row, optional

Image 
==========
id  -- autoincrement
name  -- varchar(50) or similar, non-unique
path  -- store as URI/URL, unique
description  -- varchar(128) or similar

Gallery_Image
===============
galleryId  -- fk reference to Gallery.id
imageId  -- fk reference to Image.id
         -- the pair is unique

Related_Gallery  -- optional table
================
galleryId  -- fk reference to Gallery.id
relationship  -- code, or fk reference to other table
relatedId  -- fk reference to Gallery.id
           -- entire row should be unique
           -- somewhat tricky to use.
相关问题