[英]DB2 Sql - How to join a table on a resulting field of another table
I'm trying to join two tables but I can't join field1
of table1
with field2
of table2
which is the result of a DISTINCT
instruction. 我正在尝试联接两个表,但无法将
table1
field1
与table2
field2
table2
,这是DISTINCT
指令的结果。
eg 例如
Select f1
From table1
join (Select distinct(f2) as "secondField"
From table2
) b on f1 = *X*
What can I set as X
? 我可以将
X
设置为什么? Maybe b.f2
or b.secondField
? 也许
b.f2
或b.secondField
?
If X
is a specific field I've got no problem, if it is given by a DISTINCT, SUM or similar functions I'm not able to manage it. 如果
X
是一个特定字段,那么我没有问题,如果它是DISTINCT,SUM或类似函数给出的,则无法管理它。
Can someone give me a tip? 有人可以给我小费吗?
SELECT f1
FROM table1 a
JOIN (SELECT DISTINCT(f2) as "secondField" FROM table2) b
ON a.f1 = b.secondField
Will get what you're looking for. 会得到您想要的。 Since you gave a specific name inside the sub-query, that's what you'd use (and what you would have to use, since you're using the
DISTINCT
). 既然你给了子查询中一个特定的名字,这就是你想要的使用(你将不得不使用,因为你使用的是什么
DISTINCT
)。
Have you tried joining on secondfield
? 您是否尝试过加入
secondfield
? Please see the following: 请参阅以下内容:
Select f1
From table1
join (Select distinct(f2) as "secondField"
From table2
) b on b.secondField = table1.f1
Simply if you are using an aggregate function such as Distinct, Count, Max, etc. in a sub-query, give the aggregate an alias and use this alias in the join statement. 只需在子查询中使用聚合函数(例如Distinct,Count,Max等),即可为聚合提供别名,并在join语句中使用此别名。
It looks like what you are trying to do might be written simpler as: 看起来您尝试做的事情可能更简单地写为:
SELECT f1
FROM table1 a
WHERE f1 IN (SELECT f2 as "secondField" FROM table2)
Or 要么
SELECT f1
FROM table1 a
WHERE f1 IN (SELECT DISTINCT(f2) as "secondField" FROM table2)
One of these may be faster than your JOIN 其中之一可能比您的JOIN快
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.