我有两张桌子:
人员表:
---------------------
|Person_ID | Phone_ID |
|---------------------|
|1234 | 12 |
|345 | 10 |
|43 | 33 |
|55 | 27 |
-----------------------
电话表:
--------------------------
|Phone_ID | Phone_Number |
|--------------------------|
| 12 | null |
| 10 | 9876 |
| 33 | 9654 |
| 27 | null |
--------------------------
执行查询时:
select t1.person_id, t2.phone_id
from person t1
left join
phone t2
on t1.phone_id=t2.phone_id;
我得到了结果:
--------------------------
| Person_ID | Phone_number |
|--------------------------|
| 1234 | null |
| 345 | 9876 |
| 345 | null |
| 43 | 9654 |
| 43 | null |
| 55 | null |
--------------------------
如何消除已经拥有电话号码的人员ID获取null
值的问题?
答案 0 :(得分:0)
your query do not return that results.
很可能您的手机和人表格与预期不符。
您应该截断这些表并重新插入数据。然后重新执行您的查询。
truncate table Person ;
truncate table Phone ;
insert into person
select 1234 ,12 from dual union all
select 345, 10 from dual union all
select 43 , 33 from dual union all
select 55 , 27 from dual ;
commit;
insert into phone
select 12 , null from dual union all
select 10 , 9876 from dual union all
select 33 , 9654 from dual union all
select 27 ,null from dual ;
commit;
select t1.person_id, t2.phone_id
from person t1
left join phone t2
on t1.phone_id=t2.phone_id;
答案 1 :(得分:0)
您的查询运行良好,因为我已经检查过动态创建表,试试这个,直接在查询窗口中运行:
DECLARE @persons TABLE (
person_id INT,
phone_id INT )
DECLARE @phones TABLE (
phone_id INT,
phonenumber BIGINT )
INSERT INTO @persons VALUES(1234,12),(345,10),(43,33),(55,27)
INSERT INTO @phones VALUES(12,null),(10,9876),(33,9654),(27,null)
SELECT * FROM @persons
SELECT * FROM @phones
select t1.person_id, t2.phone_id
from @persons t1
left join
@phones t2
on t1.phone_id=t2.phone_id;
如果您需要消除包含条目的null
,您可以在最后使用条件:
WHERE 'column_name' IS NOT NULL
或者如果要将null替换为空白或某些值,可以使用:
ISNULL(column_name,'replacement_value') AS new_col_name
答案 2 :(得分:0)
WITH actual_phones AS
( SELECT phone_id, phone_number
FROM phone
WHERE phone_number IS NOT NULL )
SELECT person_id, phone_number
FROM person NATURAL JOIN actual_phones
UNION
SELECT person_id, null AS phone_number
FROM person
WHERE phone_id NOT IN ( SELECT phone_id
FROM actual_phones );