[英]Select involving Many-to-many table
I have 3 tables: products, features and linking table (many-to-many) For example, I need to get from linking table all products, which have 3 features with id = 1, 2 and 3 我有3个表:产品,功能和链接表(多对多)例如,我需要从链接表中获取所有产品,这些产品具有id = 1、2和3的3个功能
link_id | product_id | feature_id
---------------------------------
100 | 1 | 1
101 | 1 | 2
102 | 1 | 3
Guys, what's the simplest way to write query? 伙计们,写查询的最简单方法是什么?
SELECT pr.* FROM product pr, link lk WHERE pr.id = lk.product_id
AND lk.feature_id = 1 AND lk.feature_id = 2 AND lk.feature_id = 3
Doesn't work 不起作用
As you are checking the values for three different records, you can't check them all on all records. 在检查三个不同记录的值时,不能在所有记录上全部检查它们。
Make three joins, one agains a link record for each feature: 进行三个联接,再一次为每个功能记录一个链接:
select
pr.*
from
product pr
inner join link lk1 on pr.id = lk1.product_id and lk1.feature_id = 1
inner join link lk2 on pr.id = lk2.product_id and lk2.feature_id = 2
inner join link lk3 on pr.id = lk3.product_id and lk3.feature_id = 3
Do it like this: 像这样做:
SELECT pr.* FROM product pr, link lk
WHERE pr.id = lk.product_id
AND lk.feature_id IN ( 1, 2, 3)
with ur;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.