需要MySQL语法帮助

时间:2014-05-01 22:16:28

标签: mysql sql relational-division

我完全坚持这一点,并希望得到一些比我更流利的人的帮助!

情况:我的图片最多可以包含3个类别。我必须使用类别名称(例如“学校”)查找它们。我有一个Image表,一个Category表和一个CategoryImage表作为连接表

基本字段是

Category
    Id
    categoryname
Image
    Id
    imagename
    description
CategoryImage
    categoryId
    imageId

如果图像'001'属于名为'School'和'Home'的类别,它将在CategoryImage中有2个条目。

我需要sql来查找“学校”和“主页”类别中的所有图像。我可以看到这个sql可能正在尝试返回单个图像,其中类别为“School AND'Home”,这显然是不可能的。 [将AND更改为OR会查找记录到'School'类别的图像以及属于'Home'类别的图像,这不是我需要的。

SELECT 
   DISTINCT t0.description, 
   t0.imagename
FROM 
   Image t0, Category T2, CategoryImage T1 
WHERE 
  (T2.name = "School" 
  AND T2.name = "Home")  
  AND T1.categoryId = T2.id 
  AND t0.id = T1.imageId 

提前感谢任何建议。

4 个答案:

答案 0 :(得分:0)

尝试这样的事情:

select distinct t0.description 
     , t0.imagename 
from categoryimage T1 
join image t0 on t0.id = T1.imageid 
join category T2 on T1.categoryid = T2.id 
where  T2.name in ( 'School', 'Home') 

答案 1 :(得分:0)

这将为您提供学校和家庭类别中的所有图像

SELECT 
   i.description, 
   i.imagename
FROM 
   Image i
WHERE EXISTS (SELECT * 
              FROM Category c 
              INNER JOIN CategoryImage ci ON ci.categoryid=c.id 
              WHERE ci.imageid=i.id AND c.name="School")
   AND EXISTS (SELECT * 
              FROM Category c 
              INNER JOIN CategoryImage ci ON ci.categoryid=c.id 
              WHERE ci.imageid=i.id AND c.name="Home")

答案 2 :(得分:0)

SELECT 
  t0.description, t0.imagename
FROM 
  Image t0 
  INNER JOIN CategoryImage T1 ON (t0.id = T1.imageId)
  INNER JOIN Category T2 ON (T1.categoryId = T2.id)
WHERE 
  T2.name = "School"
UNION
SELECT 
  t0.description, t0.imagename
FROM 
  Image t0 
  INNER JOIN CategoryImage T1 ON (t0.id = T1.imageId)
  INNER JOIN Category T2 ON (T1.categoryId = T2.id)
WHERE 
  T2.name = "Home"

答案 3 :(得分:0)

SELECT DISTINCT(i.description), i.imagename 
FROM CategoryImage ci 
LEFT JOIN Category c
ON ci.categoryId = c.Id
LEFT JOIN Image i 
ON ci.imageId = i.Id
WHERE c.categoryname IN ( 'School', 'Home' )