Reputation: 211
I am running into an issue and it is making me a bit crazy. I have the following code:
SELECT COUNT(DISTINCT f.f_id) AS `The Good`,
COUNT(DISTINCT s.f_id) AS `The Bad`,
COUNT(DISTINCT x) AS `The Ugly"`
FROM faculty f, student s, (
SELECT f_id AS x
FROM faculty
MINUS (
SELECT f.f_id
FROM faculty f, course_section cs
WHERE f.f_id = cs.f_id
UNION
SELECT f_id
FROM student
)
);
I am trying to get a count of f_id
's from faculty table, f_id
's from student
table, and then a count of f_id
's from faculty
table MINUS
f_id
's from the student table and course_section
table.
All is well if my last COUNT
returns a number that is not 0
. However, if it returns a 0
it also changes my first two counts to a 0
. The first two COUNT
s should be 6
and 4
respectively.
I have been trying to figure out how to fix this for a couple of hours but am having no luck.
Obviously there must be something that I am missing. What is wrong with my code?
Thanks.
Upvotes: 1
Views: 69
Reputation: 86755
You're using ANSI-ANCIENT notation for the joins TableA, TableB, TableC
.
But you don't have a WHERE clause. That's joining all the tables with every possible combination of rows (A full cartessian product). That's a bad idea.
Also, your results don't actually require any of the tables to be joined together. I'd recommend just using sub-queries in the SELECT clause...
SELECT
(select count(distinct f_id) from faculty) "The Good",
(select count(distinct f_id) from student) "The Bad",
(
select
count(distinct f_id)
from
(
select f_id from faculty
MINUS
select f.f_id from faculty f INNER JOIN course_section cs ON f.f_id = cs.f_id
MINUS
select f_id from student
)
) "The Ugly"
;
-- Add FROM DUAL is this is Oracle.
Upvotes: 1