我有四张桌子。我需要从所有这些数据中获取数据。表'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的出现次数。 'Houses'包含租户占用的房屋详细信息。表'众议院'和'个人资料'没有直接关联,而是通过表格'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)
答案 0 :(得分:1)
试试这个:
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
答案 1 :(得分:1)
只需删除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)
答案 2 :(得分:1)
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;