Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL多对多,如何检查多行上的条件_Sql_Sql Server_Tsql_Sql Server 2008 R2 - Fatal编程技术网

SQL多对多,如何检查多行上的条件

SQL多对多,如何检查多行上的条件,sql,sql-server,tsql,sql-server-2008-r2,Sql,Sql Server,Tsql,Sql Server 2008 R2,在多对多表中,如何查找所有条件都匹配的ID,但可能一行匹配一个条件,而另一行匹配另一个条件 例如,假设我有一个将购物车映射到产品的表,以及另一个定义产品的表 我如何才能找到一个购物车,至少有一个匹配的每个标准 例如,条件可以是像“%fruit%”这样的product.category,像“%vegeture%”这样的product.category,等等 最终,我想取回购物车ID,可以是所有这些ID,但在我的具体情况下,我很乐意得到任何匹配ID,其中至少有一个匹配项。我假设一个名为cart\u

在多对多表中,如何查找所有条件都匹配的ID,但可能一行匹配一个条件,而另一行匹配另一个条件

例如,假设我有一个将购物车映射到产品的表,以及另一个定义产品的表

我如何才能找到一个购物车,至少有一个匹配的每个标准

例如,条件可以是像“%fruit%”这样的product.category,像“%vegeture%”这样的product.category,等等


最终,我想取回购物车ID,可以是所有这些ID,但在我的具体情况下,我很乐意得到任何匹配ID,其中至少有一个匹配项。

我假设一个名为cart\u per\u product的表带有cart,product字段,一个名为product的表带有product,category字段

select cart from cart_per_product c
where exists 
(
    select 1 from product p1 where p1.product=c.product and p1.category like N'%fruit%'
)
and exists 
(
    select 1 from product p2 where p2.product=c.product and p2.category like N'%vegetable%'
)
可以将and运算符与外部联接结合使用。M:N关系上的A:

select p.name
  from products p
 where id_product = ALL    -- all operator 
 (  select pc.id_product
     from categories c 
     left outer join product_category pc on pc.id_product = p.id_product and
                                          pc.id_category = c.id_category
 )

我想你可以算出列名

select c.id 
from cart c
join product p 
  on c.pID = p.ID 
group by c.id 
having count(distinct p.catID) = (select count(distinct p.catID) from product)

可能不是最有效的通用方法:

with data as (
    select *,
        count(case when <match condition> then 1 end)
            over (partition by cartid) as matches
    from <cart inner join products ...>
)
select * from data
where matches > 0;

你能提供一个你的模式,你的数据和你想得到什么的例子吗?