我对 SQL 语句有疑问。我有属于一个类别(实体)的实体画廊。然后我有实体 GalleryImages 并且存储了特定画廊的图像。图库可以有很多图片,但图库也可以没有图片(还没有添加图片)。
现在我想构建 SQL 查询来选择具有一个或多个图像并且属于某个类别的 (DESC) Gallery。
类别(ID、名称)
图库(id、名称、category_id)
GalleryImages(id,gallery_id,路径)
类别 -> 图库(一对多)图库 -> GalleryImages(一对多)
我对 SQL 语句有疑问。我有属于一个类别(实体)的实体画廊。然后我有实体 GalleryImages 并且存储了特定画廊的图像。图库可以有很多图片,但图库也可以没有图片(还没有添加图片)。
现在我想构建 SQL 查询来选择具有一个或多个图像并且属于某个类别的 (DESC) Gallery。
类别(ID、名称)
图库(id、名称、category_id)
GalleryImages(id,gallery_id,路径)
类别 -> 图库(一对多)图库 -> GalleryImages(一对多)
嗯 - 看起来基本问题已经得到解答。但是你的设置让我有点不快......
我想我会稍微重组一下你的表格(假设国际化不是问题)。除其他外,我认为“类别”和“画廊”的概念之间没有根本区别。现在,可能有“超级”和“子”类别/画廊,并且图像可能同时属于多个(即,来自 Renniasance、米开朗基罗、雕塑等)。它类似于标签的概念。
我可能会将您的表格修改为:
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.
尝试这个:
SELECT *
FROM Gallery as G
WHERE
G.category_id = 1
AND G.id in (SELECT gallery_id FROM GalleryImages )
将 1 替换为您要选择的 caregory_id。