Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/68.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_Inner Join_Aggregate Functions_Having Clause - Fatal编程技术网

SQL-基于另一个表的树结构删除一个表的结果

SQL-基于另一个表的树结构删除一个表的结果,sql,inner-join,aggregate-functions,having-clause,Sql,Inner Join,Aggregate Functions,Having Clause,为了更好地定义我要问的问题,向您介绍我正在使用的数据可能会更容易 基本上,我有两个表连接起来,看起来像这样: 表1 Product ID AccountLinkID (FK) PRODUCT00001 AC000001 PRODUCT00001 AC000002 PRODUCT00001 AC000003 PRODUCT00001 AC000004 表2 Link (FK) AccountType AC000001 1 AC000002 2 AC000

为了更好地定义我要问的问题,向您介绍我正在使用的数据可能会更容易

基本上,我有两个表连接起来,看起来像这样:

表1

Product ID    AccountLinkID (FK)
PRODUCT00001  AC000001
PRODUCT00001  AC000002
PRODUCT00001  AC000003
PRODUCT00001  AC000004
表2

Link (FK)     AccountType
AC000001      1
AC000002      2
AC000003      3
AC000004      4
作为我正在查看的某些数据的一部分,我希望确保如果任何ProductID链接到帐户类型“4”,则该ProductID将从搜索中删除

问题是外键也不是一个数字,因为一个产品可以链接到多个帐户类型(例如,一个产品可以链接到卖方帐户、买方帐户、客户帐户等)

因此,在本例中,帐户类型4类似于“虚拟”帐户,因此链接到它的任何productID都不是我希望包含在搜索中的ID

我想不出如何使用帐户类型来删除产品id


提前感谢您的建议。

如果您希望每个
productid
只包含一行,您可以使用
having
子句加入、聚合和筛选

select t1.productid
from table1 t1
inner join table2 t2 on t2.link = t1.accountlinkid
group by t1.productid
having max(case when t2.accounttype = 4 then 1 else 0 end) = 0
另一方面,如果希望从
t1
中获得整行,则窗口函数是更好的选择:

select t.*
from (
    select t1.*, 
        max(case when t2.accounttype = 4 then 1 else 0 end) over(partition by t1.productid) has_type4
    from table1 t1
    inner join table2 t2 on t2.link = t1.accountlinkid
) t
where has_type4 = 0

欢迎@A-R。如果我的答案回答了您的问题,请单击复选标记。。。谢谢