0

我有两张桌子,有firstname,lastnameamount

我可以做一个左连接:

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

为什么不?

4

6 回答 6

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 ; 
于 2012-12-07T18:56:59.740 回答
2

dp.amount 不存在,因为您在您的select * from (select * from...)

那组括号内的括号创建了一个派生表,因此您对 dp 的引用不存在于这些括号之外。把你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;
于 2012-12-07T18:57:34.617 回答
1

实际上你不需要使用sub querywhere dp 不存在。

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

编辑:这里有一些关于 JOIN 的好例子

于 2012-12-07T18:58:17.310 回答
0
select * from (
   select * from ....
   where dp.amount is null;
)
于 2012-12-07T19:02:27.187 回答
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;
于 2012-12-07T18:59:53.597 回答
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;
于 2012-12-07T19:05:18.467 回答