我有3张桌子:
product
表格中有一个字段group_id
(是产品组)。
movement_product
表包含一个字段movement_id
(与movement
表匹配)和product_id
(与product
表匹配)。
我想选择一个机芯的所有机芯产品,如果其中一个机芯来自特定产品组。
我尝试了以下SQL:
SELECT
mp.*
FROM
movement AS m,
movement_product AS mp
WHERE
m.id = mp.movement_id
AND EXISTS (
SELECT *
FROM product p
WHERE mp.product_id = p.id
AND p.group_id = "48"
)
GROUP BY mp.movement_id
但是它返回的列表只是来自该特定组的产品(group_id上的48只是一个例子)。
答案 0 :(得分:0)
如果我理解正确,你可以遵循这个逻辑。首先,要获得符合条件的所有动作:
select distinct mp.movement_id
from movement_products mp
where exists (select 1
from products p
where p.id = mp.product_id and
p.group_id = 48
);
要获得这些动作中的产品,您可以这样做:
select mp.*
from movement_products mp
where mp.movement_id in (select mp.movement_id
from movement_products mp
where exists (select 1
from products p
where p.id = mp.product_id and
p.group_id = 48
);