[英]sql case self join
Using oracle The following is a simple version of my code for a self-joined table. 使用oracle以下是我的自连接表代码的简单版本。 There's no reason for a self-join but I was left with the code and it returned unintended results.
没有理由进行自我联接,但是我留下了代码,并且它返回了意外的结果。 I've made the fix in my code but I want to understand what's going on.
我已经在代码中进行了修复,但是我想了解发生了什么。
I will get a 'yes' or 'no' depending on what aliases table I chose for the field population in the case statement. 根据在case语句中为字段填充选择的别名表,我将得到“是”或“否”。
The below returns a 'yes' but I don't want to move there if population = 'high'. 下面的内容返回“是”,但如果人口 =“高”,我不想搬到那里。
I don't understand? 我听不懂 I suspect alias b is not being evaluated in the case statement but why?
我怀疑别名b没有在case语句中进行评估,但是为什么呢?
SELECT a.name,
a.continent,
a.population,
case
when b.population = 'high' then 'no'
else 'yes'
end "move there?"
FROM world a,
world b
The query in your question doesn't specify how world a
is supposed to be joined to world b
, and as such ALL RECORDS IN a
are being joined to ALL RECORDS IN b
. 您问题中的查询未指定将
world a
与world b
联接的方式,因此,将a
中的ALL RECORDS与b
ALL RECORDS联接。 This is known as a Cartesian join or a CROSS JOIN
, and if you were to use ANSI-style joins it would be coded as: 这称为笛卡尔
CROSS JOIN
或CROSS JOIN
,如果要使用ANSI样式的联接,则将其编码为:
SELECT a.name,
a.continent,
a.population,
case
when b.population = 'high' then 'no'
else 'yes'
end "move there?"
FROM world a
CROSS JOIN world b
This is probably not what was intended. 这可能不是预期的。 :-)
:-)
I suspect that what was wanted was to do an INNER JOIN. 我怀疑想要的是做一个内部联接。 Using ANSI-style joins this would be something like
使用ANSI样式的连接将类似于
SELECT a.name,
a.continent,
a.population,
case
when b.population = 'high' then 'no'
else 'yes'
end "move there?"
FROM world a
INNER JOIN world b
ON b.name = a.name
or, using the 'implied' join style 或者,使用“隐式”联接样式
SELECT a.name,
a.continent,
a.population,
case
when b.population = 'high' then 'no'
else 'yes'
end "move there?"
FROM world a,
world b
WHERE b.name = a.name
Best of luck. 祝你好运。
Explicit Join and ON 显式加入并开启
SELECT a.name,
a.continent,
a.population,
case
when b.population = 'high' then 'no'
else 'yes'
end "move there?"
FROM world a
inner join world b
on b.<col> = a.<col>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.