繁体   English   中英

关于INNER JOIN的Where子句

[英]Where clause on INNER JOIN

我有四张桌子。 我需要从所有这些数据中获取数据。 'Tenancy_histories'包含move_in_date,move_out_date,rent列。 “配置文件”包含first_name,last_name,email,profile_id等。 “引用”包含referrer_bonus_amount和类似的其他数据。

最重要的是,它包含特定profile_id所引用的引用数,该引用数是'referrer_id(与profile id相同)列中该profile_id的出现次数。 '房屋'包含租户占用的房屋细节。 '房屋''个人资料'没有直接关联,而是通过表'Tenancy_histories'链接

我需要写一个查询来获取尚未提及一次的租户的姓名,联系方式,城市和房屋详细信息。

我试过这样的事情,但没有得到所需的输出,虽然没有得到任何错误

SELECT
    pr.first_name + ' ' + pr.last_name AS full_name, pr.phone, 
    pr.[city(hometown)], hs.bhk_details 
FROM
    Profiles pr  
INNER JOIN 
    Tenancy_histories th ON pr.profile_id = th.profile_id 
INNER JOIN 
    Houses hs ON th.house_id = hs.house_id 
INNER JOIN 
    Referrals rf ON pr.profile_id = rf.[referrer_id(same as profile id)] 
WHERE 
    pr.profile_id NOT IN (SELECT [referrer_id(same as profile id)] 
                          FROM Referrals)

尝试这个:

select full_name , phone,[city(hometown)], bhk_details ,profile_id 
from (
select p.full_name , p.phone,p.[city(hometown)], p.bhk_details ,p.profile_id
from (
select pr.first_name+' '+pr.last_name as full_name, pr.phone, pr.[city(hometown)], hs.bhk_details ,pr.profile_id
from Profiles pr 
INNER JOIN 
Tenancy_histories th 
on pr.profile_id = th.profile_id 
INNER JOIN 
Houses hs 
on th.house_id = hs.house_id 
) as p
left join
Referrals rf 
on p.profile_id = rf.[referrer_id(same as profile id)] 
where rf.[referrer_id(same as profile id)] is null
) as p_r

简单地删除INNER JOIN到推荐表就可以了

SELECT
    pr.first_name + ' ' + pr.last_name AS full_name, 
    pr.phone, 
    pr.[city(hometown)], 
    hs.bhk_details 
FROM
    Profiles pr  
INNER JOIN 
    Tenancy_histories th ON pr.profile_id = th.profile_id 
INNER JOIN 
    Houses hs ON th.house_id = hs.house_id 
WHERE 
    pr.profile_id NOT IN (SELECT [referrer_id(same as profile id)] 
                          FROM Referrals)

NOT IN子查询是危险的。 如果子查询中的任何行返回NULL值,则不会返回任何行。

除了将inner join移除到referrals ,我建议将比较更改为使用NOT EXISTS

WHERE NOT EXISTS (SELECT 1
                  FROM referrals
                  WHERE pr.profile_id = r.[referrer_id(same as profile id)] 
                 );

另一种方法是使用LEFT JOIN进行referrals ,只需检查是否匹配:

SELECT pr.first_name + ' ' + pr.last_name AS full_name, pr.phone, 
       pr.[city(hometown)], hs.bhk_details 
FROM Profiles pr INNER JOIN 
     Tenancy_histories th
     ON pr.profile_id = th.profile_id INNER JOIN 
     Houses hs
     ON th.house_id = hs.house_id LEFT JOIN 
     Referrals rf
     ON pr.profile_id = rf.[referrer_id(same as profile id)] 
WHERE rf.[referrer_id(same as profile id)] IS NULL;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM