Problem in Joining tables
I have three tables called SData, Schdata and Fordata and the data look开发者_StackOverflows like:
SData: Schdata Fordata
Name Pro_ID Pro_ID Sch_ID Str_ID Sch_ID
ACase 258 258 438 6 654
Boece 369 125 125 7 438
Dremd 781 369 985 12 548
Wep 469 469 754 8 284
PQData
Pro_ID Sch_ID Type
258 438 rep
358 678 pro
Now I am trying to get the Names from SData where the Pro_ID exists in Schdata and I don't want the Pro_ID from Schdata which has the Shc_ID from Fordata so My output should be:
Name Sch_ID
Boece 985
Wep 754
So I wrote a query something like this:
Select a.Name,s.Sch_ID
From SData a
Inner Join Schdata s
on a.Pro_ID = s.Pro_ID
Inner Join Fordata f
on f.Sch_ID <> s.Sch_ID
But I don't know whether I am doing it right. can anyone help me?
You were almost there:
Select a.Name,s.Sch_ID
From SData a
Inner Join Schdata s
on a.Pro_ID = s.Pro_ID
where not exists (select f.Sch_ID from Fordata f
where f.Sch_ID = s.Sch_ID )
[See Martin's comment below] The right way would to do it would be:
Select a.Name,s.Sch_ID
From SData a
Inner Join Schdata s
on a.Pro_ID = s.Pro_ID
WHERE NOT EXISTS (SELECT 1 FROM Fordata f
WHERE f.Sch_ID = s.Sch_ID)
One solution using OUTER/INNER JOINs:
DECLARE @SData TABLE
(
Name VARCHAR(25) NOT NULL
,Pro_ID INT NOT NULL
);
INSERT @SData
VALUES ('ACase',258),('Boece',369),('Dremd',781),('Wep',469);
DECLARE @Schdata TABLE
(
Pro_ID INT NOT NULL
,Sch_ID INT NOT NULL
);
INSERT @Schdata
VALUES (258,438), (125,125), (369,985), (469,754);
DECLARE @Fordata TABLE
(
Str_ID INT NOT NULL
,Sch_ID INT NOT NULL
);
INSERT @Fordata
VALUES (6,654), (7,438), (12,548), (8,284);
SELECT a.Name, b.Sch_ID
FROM @Schdata b
LEFT OUTER JOIN @Fordata c ON b.Sch_ID = c.Sch_ID
INNER JOIN @SData a ON a.Pro_ID = b.Pro_ID
WHERE c.Sch_ID IS NULL
精彩评论