2012-04-09 33 views
0

我有一個SQL句子的問題。我有屬於一個類別(實體)的實體畫廊。然後我有實體GalleryImages,並且存儲特定圖庫的圖像。圖庫可以有很多圖像,但圖庫也可以不存在圖像(不添加圖像)。selecta畫廊有一個或多個圖像

現在我想要構建SQL查詢來選擇(DESC)具有一個或多個圖像並屬於某個類別的圖庫。

類別(ID,姓名)

畫廊(ID,姓名,CATEGORY_ID)

GalleryImages(ID,gallery_id,路徑)

分類 - >畫廊(一對多) 畫廊 - > GalleryImages(一對多)

回答

0

嘗試這種情況:

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

將1替換爲您要選擇的caregory_id。

+0

我嘗試這樣做,但這種查詢選擇最新圖庫不管畫廊有圖片或不:「選擇P檔FROM NewsAdminBundle:畫廊p其中p .category_id =:category AND p.id IN(SELECT i FROM NewsAdminBundle:GalleryImages i)ORDER BY p.created_at DESC' – repincln 2012-04-09 20:16:42

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. 
+0

感謝您對提示的回覆。我忘了提及,我也有一個新聞實體,該實體中的文章屬於類別。畫廊也屬於這一類(即科學,文化......)。所以我有類別,所以新聞如畫廊屬於這些類別。 – repincln 2012-04-09 20:21:58

+0

@repincln - 那麼是的,他們可能是不同的實體(取決於你如何概念化)。但是請記住,新聞實體可能屬於多個不同的類別。這裏顯示的畫廊技術應該適用於您的新聞類別。 – 2012-04-09 20:34:03