我的SQL语句有问题。我有实体Gallery属于一个类别(实体)。然后我有实体GalleryImages,并存储特定图库的图像。图库可以包含大量图像,但图库也可以不存在图像(尚未添加图像)。
现在我想构建SQL查询来选择(DESC)Gallery,它有一个或多个图像并且属于某个类别。
类别(id,名称)
图库(id,name,category_id)
GalleryImages(id,gallery_id,path)
类别 - >画廊(一对多) 图库 - > GalleryImages(一对多)
答案 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)
我可能会将你的表修改为:
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.