Reputation: 5445
i am using an oracle database, i have two tables.
table A primary key = productid
table B references productid of table A
primary key = imageid
flow:
each product should have 4 images stored in the table B (mandatory)
problem:
there are some products that has only 2 or sometimes 3 or sometimes 1 image only despite of the fact that the 4 images rule is mandatory based from code level.
Question:
how to count unique number of products that has images in table b?Because, if I do
select count(*) from tableA join tableB on tableA.productid = tableB.productid
the result is double, because it's a one to many...as in , one product has many images.
So let's say productID = 12345
has 4 images
in table B
, once I ran my query, the result is 4 , when i want to only get 1...so how?
Upvotes: 0
Views: 99
Reputation: 10236
SELECT Count(DISTINCT TableA.productid)
FROM TableA
JOIN TableB ON TableA.productid = TableB.productid;
Upvotes: 2
Reputation: 1062
SELECT COUNT(*) FROM
(
select A.productId from tableA A join tableB B on A.productid = B.productid
GROUP BY A.productId
HAVING COUNT(B.imageId) > 1 ) T
Upvotes: 0
Reputation: 11527
Do a sub query with where exists
select count(*) from tableA
where exists (select 1 from tableB where tableA.productid = tableB.productid)
Upvotes: 1