MySQL Select 全部来自 Table 1,其中外键不存在或不等于指定的键
MySQL Select all from Table 1 where Foreign key not exists or is not equal to specified key
您好,我不知道如何编写此 select 语句。
我有以下架构:
table11:ntable2n:1table3
所以我在 table 1 和 3 之间得到了一个 n:m
我现在想做的是通过 table 2 获取 table 1 中与 table 3 没有关系的所有条目,或者如果存在关系,我只想要那些没有关系的条目匹配一个特定的 table 3 主键。
或者换句话说,如果 table 1 是产品而 table 3 是订单,我想取出所有未按照我给 select 的特定订单放置的产品。
我已经尝试了多种 select 命令,但其中 none 可以正常工作,对我来说最难的是 'not equals orders_id' 部分,到目前为止我只得到一个空的 table 作为结果。
我画了一幅小画,这样你可以更好地理解我想做什么。
我会推荐 not exists
:
select p.*
from products p
where not exists (
select 1
from product_orders po
where po.product_id = o.product_id and po.order_id = ?
)
问号表示您作为查询参数提供的订单 ID。
我怀疑您是否需要 table orders
来生成您想要的结果 - 除非您通过主键以外的其他列来标识顺序。如果是这样,那就是:
select p.*
from products p
where not exists (
select 1
from product_orders po
inner join orders o on o.order_id = po.order_id
where po.product_id = o.product_id and o.<somecol> = ?
)
您好,我不知道如何编写此 select 语句。
我有以下架构:
table11:ntable2n:1table3
所以我在 table 1 和 3 之间得到了一个 n:m
我现在想做的是通过 table 2 获取 table 1 中与 table 3 没有关系的所有条目,或者如果存在关系,我只想要那些没有关系的条目匹配一个特定的 table 3 主键。
或者换句话说,如果 table 1 是产品而 table 3 是订单,我想取出所有未按照我给 select 的特定订单放置的产品。
我已经尝试了多种 select 命令,但其中 none 可以正常工作,对我来说最难的是 'not equals orders_id' 部分,到目前为止我只得到一个空的 table 作为结果。
我会推荐 not exists
:
select p.*
from products p
where not exists (
select 1
from product_orders po
where po.product_id = o.product_id and po.order_id = ?
)
问号表示您作为查询参数提供的订单 ID。
我怀疑您是否需要 table orders
来生成您想要的结果 - 除非您通过主键以外的其他列来标识顺序。如果是这样,那就是:
select p.*
from products p
where not exists (
select 1
from product_orders po
inner join orders o on o.order_id = po.order_id
where po.product_id = o.product_id and o.<somecol> = ?
)