SQL:一对多,其中一个Many关系有两个特定值

时间:2014-12-09 11:07:45

标签: mysql sql select join one-to-many

我想从表A中获取所有记录,其中' some_value'和' some_other_value'表B中存在两个不同的列(对于同一记录) - 但是对于表A中具有特定值的记录的表A中的每个记录,我还希望表B中的所有其他记录属于记录在表A中。

一个例子: 我有一个用户表(表A)和一个图像表(表B)。我想要所有用户及其所有图像,其中至少有一个图像被称为" some-name.png"并且该图像类型是"个人资料图片"。

以下内容不会为具有此特定图片的用户提供所有其他图片

SELECT * 
FROM users  
JOIN images
ON users.id = images.user_id
WHERE images.name = 'some-name.png' 
   AND images.type = 'profile picture'
GROUP BY users.id 

3 个答案:

答案 0 :(得分:0)

试试这个:

SELECT * 
FROM users u 
LEFT JOIN images i ON u.id = i.user_id AND i.name = 'some-name.png' AND i.type = 'profile picture'
GROUP BY users.id 

答案 1 :(得分:0)

尝试此查询:

SELECT *
FROM   users u
       JOIN images i
         ON u.id = i.user_id
WHERE  EXISTS (SELECT user_id
               FROM   images i1
               WHERE  u.id = i1.user_id
                      AND i1.name = 'some-name.png'
                      AND i1.type = 'profile picture')
       AND i.type = 'profile picture' ;

示例sqlfiddle

答案 2 :(得分:0)

select * from images I
JOIN (
select distinct U.* from users U
join images SI
on U.id = SI.user_id
where SI.name = 'some-name.png'
and SI.type = 'Prpfile picture') as SIU
ON SIU.id = I.user_id

Fiddle here