簡體   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