MySql从分组表中选择

时间:2016-10-20 17:41:47

标签: mysql sql

我有桌子:狗,主人和狗主,其中包含哪个主人有狗的信息。

 ___Dog__    _Owner__    ___Dogowner___
 |id|name|   |id|name|   |id|dog|owner|
 |1 |dog1|   |1 |own1|   |1 | 2 | 1   |
 |2 |dog2|   |2 |own2|   |2 | 1 | 2   |
                         |3 | 2 | 2   |

我想只选择可以自由选择的狗。例如,own1有dog2,所以他只能看到dog1 avaible。 Own2有dog1和dog2所以他不能再选择了。

我尝试过应该返回0行的查询,但结果我总是有一行:

select a.id as id, a.dog as dog from dog a left join dogowner b on a.id=b.dog WHERE b.owner<>'2' group by b.dog

也许首先我必须将狗狗表分组然后选择?

2 个答案:

答案 0 :(得分:1)

您可以不在

中使用
select a.id as id, a.dog as dog 
from dog a 
left join dogowner b on a.id=b.dog 
WHERE b.owner<>'2' 
and a.id not in (select c.dog 
            from dogowner c where c.owner = b.owner)

答案 1 :(得分:0)

你也可以交叉加入Dog and Owner,然后离开加入DogOwner并寻找null DogOwner id。

SELECT  d.id,
        d.name
FROM    Dog d
        CROSS JOIN Owner o
        LEFT JOIN DogOwner do ON do.dog = d.id
                                 AND do.owner = o.id
WHERE   do.id IS NULL