![](/img/trans.png)
[英]Query records in one table that exists in either of two columns in another table
[英]select rows whose value matches with either of the two columns in the second table:
我有一张看起来像这样的桌子。
id name
1 firstName
2 secondName
3 thirdName
4 fourthName
我想保留名称出现在第二个表中的“testName”或“prodName”列中的所有行,如下所示:
testName prodName coordinates
firstName EN 124
random secondName 1244
thirdName DE 689
FifthName DE 457
我想要一个如下所示的结果表:
id name coordinates
1 firstName 124
2 secondName 1244
3 thirdName 689
如果我只与 table2 中的另一列进行比较,这样的事情就有效:
(select *
from `table1`
where exists
(select 1
from `table2` where testName = `table1`.name ));
但这会引发错误:
(select *
from `table1`
where exists
(select 1
from `table2` where testName = `table1`.name OR prodName = `table1`.name ));
LEFT SEMI JOIN cannot be used without a condition that is an equality of fields from both sides of the join.
请试试这个:
SELECT
A.id
,A.name
,B.coordinates
FROM table1 A
INNER JOIN table2 B
ON A.name=B.testName OR A.name=B.prodName
您告诉过您还需要字段coordinate
,这在 table2 中不是唯一的。 这里是一个获取coordinate
最大值的例子。 数据库中没有第一个条目,只有另一列中第一个日期的值等。您没有指定!
With table1 as
(Select row_number() over() as id, * from unnest(["firstName","secondName","thirdName","fourthName"]) name
),table2 as
(select * from
(select "firstName" as testname, "NB" as prodName
union all select "BG","secondName") ,
unnest(generate_array(1,1)) as coordinates
)
SELECT
A.id
,A.name
,max(B.coordinates),
max(C.coordinates) as C_coordinates,
avg(ifnull(B.coordinates,C.coordinates)) as coordinate_new,
FROM table1 A
left JOIN table2 B
ON A.name=B.testName
left JOIN table2 C
ON A.name=C.prodName
group by 1,2
having coordinate_new is not null
以下是使用Where
过滤器的示例:
With table1 as
(Select row_number() over() as id, * from unnest(["firstName","secondName","thirdName","fourthName"]) name
),table2 as
(select "firstName" as testname, "NB" as prodName
union all select "BG","secondName")
select *
from `table1`
where exists
(select 1 from `table2` where testName = `table1`.name
union all Select 1 from table2 where prodName = `table1`.name )
create temp table t1 as(
select "firstName" as testName ,"EN" as prodName , 124 as coordinates union all
select "random","secondName",1244 union all
select "thirdName","DE",689 union all
select "FifthName","DE",457
);
create temp table t2 as(
select 1 as id,"firstName" as name,124 as coordinates union all
select 2,"secondName",1244 union all
select 3,"thirdName",689
);
create temp table t3 as(
select a.id as id,a.name as name from t2 as a where a.id<=0 or exists (select coordinates from t1 as b1 where a.name = b1.testName or a.name=b1.prodName)
);
select t3.id,t3.name,t2.coordinates from t3 inner join t2 on t3.name=t2.name;
查询基于您在问题中提供的任何数据。 如果这不满足您的要求,请编辑问题并添加更多详细信息,并输入您要求的示例输入 output 数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.