SQL:多对多关系,IN条件
我有一个名为 transactions 的表,通过 items_transactions 表与项目具有多对多关系。
我想做这样的事情:
SELECT "transactions".*
FROM "transactions"
INNER JOIN "items_transactions"
ON "items_transactions".transaction_id = "transactions".id
INNER JOIN "items"
ON "items".id = "items_transactions".item_id
WHERE (items.id IN (<list of items>))
但这为我提供了与列表中的一个或多个项目相关联的所有交易,并且我只希望它为我提供与所有这些项目相关联的交易。
任何帮助将不胜感激。
I have a table called transactions with a many-to-many relationship to items through the items_transactions table.
I want to do something like this:
SELECT "transactions".*
FROM "transactions"
INNER JOIN "items_transactions"
ON "items_transactions".transaction_id = "transactions".id
INNER JOIN "items"
ON "items".id = "items_transactions".item_id
WHERE (items.id IN (<list of items>))
But this gives me all transactions that have one or more of the items in the list associated with it and I only want it to give me the transactions that are associated with all of those items.
Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您必须扩展对列表中所有项目的查询:
您也许还可以使用
IN
和COUNT DISTINCT
进行处理,我不确定这样会更快。像这样的东西(完全未经测试):You have to expand out your query for all of the items in the list:
You might also be able to massage it out using
IN
andCOUNT DISTINCT
, I'm not sure which would be faster. Something like (completely untested):我想这就是你想要的。
我会将您需要的项目列表放入一张表中(临时一个就可以了)并加入其中。然后计算不同商品的数量,并将该计数与商品交易计数进行匹配。
我已经提供了示例 DDL &我用过的数据。
I think this does what you want.
I would put the list of items you need in to a table (temp one will be fine) and join on to that. Then count the number of distinct items and match the count to the item transactions count.
I've provided the sample DDL & Data that I used.
虽然这可能会扫描事务,但为每个事务嵌套相关子查询...不是特别有效,所以也许:
或者类似的方法说服数据库首先找到与至少一个项目相关的事务,然后检查每笔交易都与以后的所有项目相关联。
正如有人指出的,您也可以简单地为每个项目生成连接子句,如果项目数量不大,这可能会更好。
Although this will probably do a scan of transactions, nesting the correlated subquery for each one... not particularly efficient, so maybe:
or something similar to persuade the DB to find transactions related to at least one of the items first, and then check each transaction is linked against all the items later.
As someone's noted, you can also simply generate join clauses for each item instead, which might well be better if the number of items isn't large.
我还没有执行这个,但这应该会给你你想要的结果:
I haven't executed this, but that should get you the result you want:
查询的最后一点看起来是错误的:
“in”语句就像一个大的 OR 语句而不是 AND 语句,因此优化器将其扩展为:
编辑
我认为您需要执行项目表上的相关子查询。
The final bit of the query looks wrong:
the 'in' statement is like a big OR statement rather than an AND statement, so it is expanded by the optimizer as:
EDIT
I reckon you need to perform a correlated subquery on the items table.