选择加入时“没有这样的列”

时间:2012-12-07 18:53:59

标签: sql

我有两张包含firstnamelastnameamount的表格。

我可以进行左连接:

select * from spi left join dp 
on spi.amount = dp.amount
and lower(spi.firstname) = lower(dp.firstname)
and lower(spi.lastname) = lower(dp.lastname);

给出了很好的结果:

|#   |firstname     |lastname    |amount|dp.firstname |dp.lastname  |dp.amount
|----+--------------+------------+------+-------------+-------------+---------
|1   |saumeh synah  |s*****      |50.0  |             |             |
|2   |Neda          |M*****      |1000.0|             |             |
|3   |Mansoor       |B********** |100.0 |             |             |
|4   |Hanna         |W****       |50.0  |Hanna        |W****        |50.0
|5   |Kristen       |A****       |40.0  |Kristen      |A****        |40.0
|6   |David         |B******     |10.0  |David        |B******      |10.0

现在我想只选择dp中缺少的行。

所以我写道:

select * from ( 
select * from spi left join dp 
on spi.amount = dp.amount
and lower(spi.firstname) = lower(dp.firstname)
and lower(spi.lastname) = lower(dp.lastname) )
where dp.amount = null;

但我收到了错误

no such column: dp.amount

为什么不呢?

6 个答案:

答案 0 :(得分:3)

错误是由派生表引起的。只需尝试一个简单的查询:

select spi.* 
from spi left join dp 
on spi.amount = dp.amount
and lower(spi.firstname) = lower(dp.firstname)
and lower(spi.lastname) = lower(dp.lastname) 
where dp.amount IS null ; 

答案 1 :(得分:2)

由于您在select * from (select * from...)

中创建了派生表,因此

dp.amount不存在

该内部括号组创建了一个派生表,因此您对dp的引用不存在于这些parens之外。将你的where dp.amount = null放在最后一个括号内,然后将你的分号推到外面。

select * from ( 
select * from spi left join dp 
on spi.amount = dp.amount
and lower(spi.firstname) = lower(dp.firstname)
and lower(spi.lastname) = lower(dp.lastname) 
-- this will never find results as NULL will never equal anything
-- where dp.amount = null
where dp.amount IS NULL) AS D;

答案 2 :(得分:1)

实际上,您不需要使用不存在dp的sub query

select * from spi left join dp 
on spi.amount = dp.amount
and lower(spi.firstname) = lower(dp.firstname)
and lower(spi.lastname) = lower(dp.lastname)
WHERE dp.amount IS NULL

编辑:以下是一些nice examples about JOIN

答案 3 :(得分:0)

不确定我是否100%理解,但这会有效吗?

select dp.firstname,dp.lastname,dp.amount
from dp,spi
where dp.firstname=spi.firstname
and dp.lastname=spi.lastname
and dp.amount is null;

答案 4 :(得分:0)

select * from (
   select * from ....
   where dp.amount is null;
)

答案 5 :(得分:0)

可能是更好的名称嵌套选择:

select * from ( 
select spi.firstname, spi.lastname, spi.amount, dp.firstname f, dp.lastname l, dp.amount a from spi left join dp 
on spi.amount = dp.amount
and lower(spi.firstname) = lower(dp.firstname)
and lower(spi.lastname) = lower(dp.lastname) ) as x
where x.a = null;