简体   繁体   English

mysql 一对多反连接查询

[英]mysql one-to-many anti join query

Looking for help with a query for this situation:寻求有关此情况查询的帮助:

I have 3 tables.我有 3 张桌子。 Shoe table is a unique collection of shoe models.鞋桌是鞋款的独特集合。 Color table is a unique collection of colors a shoe could have.色表是一款独特的colors系列鞋款。 shoe_color table is a join table. shoe_color 表是一个连接表。 One shoe model can have multiple colors or just one.一只鞋 model 可以有多个 colors 或只有一个。

I am wanting to query shoe models that do not contain a particular color.我想查询不包含特定颜色的鞋款。 As an example... Shoe 1 has the colors black , red , white .例如... Shoe 1有 colors black , red , white Shoe 2 has the colors black , white . Shoe 2有 colors blackwhite Shoe 3 has the colors black , white . Shoe 3有 colors blackwhite The query for doesn't contain the color red should return the rows: Shoe 2 and Shoe 3 .不包含red的查询应返回以下行: Shoe 2Shoe 3

Any help is appreciated and please ask any questions for clarification!任何帮助表示赞赏,请提出任何问题以进行澄清!

You can use not exists .你可以使用not exists

Assuming that the join table refers to the other tables through their primary key (say color_id and shoe_id ), and that column color_name in table color stores the color name, you would go:假设连接表通过它们的主键(比如color_idshoe_id )引用其他表,并且表color中的列color_name存储颜色名称,您将 go:

select s.*
from shoe s
where not exists (
    select 1 
    from shoe_color sc 
    inner join color c on c.color_id = sc.color_id
    where sc.shoe_id = s.shoe_id and c.color_name = 'red'
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM