Link to home
Start Free TrialLog in
Avatar of bitt3n
bitt3n

asked on

how do I fix this COUNT query?

I have four tables:

shops (shop,shop_id), products(product_id,date), sex(sex,product_id), users(user_id,prior_login)

shops.shop and shops.shop_id values are unique

I wish to COUNT the number of distinct shops for which at least one row in the products table exists such that shops.shop_id=products.shop_id, sex.product_id=products.product_id, products.date >= users.prior_login, users.user_id=22, and sex.sex=0.

Right now I am trying:

SELECT COUNT (shop_id) AS total_shops FROM shops
WHERE EXISTS (
SELECT * FROM
products, sex WHERE
shops.shop_id=products.shop_id AND
sex.product_id=products.product_id AND
sex.sex=0 AND
(products.date >= (SELECT
prior_login FROM
users WHERE
user_id = 22)))

Open in new window


This produces a syntax error. What am I doing wrong?
Avatar of Michael Carrillo
Michael Carrillo
Flag of United States of America image

Your not joining your tables correctly. But to provide the correct syntax, I need to know are you using MySQL or SQL Server?
If you have SQL Server you can try:


SELECT COUNT (shop_id) AS total_shops
FROM shops
WHERE EXISTS(
SELECT *
FROM shops s inner join products p
on s.shop_id=p.shop_id
inner join sex x
on p.product_id=x.product_id
WHERE
x.sex=0 AND
(p.date >= (SELECT
prior_login FROM
users WHERE
user_id = 22)  ) )
Avatar of bitt3n
bitt3n

ASKER

I am using MySQL. Looking at your query, I'm confused why it is not necessary to correlate 'shops s' in the EXISTS query with 'shops' in the outer query. (I tried using your query in MySQL but presumably there is some syntax difference between SQL Server and MySQL that prevents it from working.)
Avatar of bitt3n

ASKER

it appears the problem was merely the space in 'COUNT (shop_id)', as when I remove this space, I get the expected result.

I'll leave this question open in case anyone wishes to suggest some other correction or improvement, but I assume the problem was just this stupid syntax mistake.
ASKER CERTIFIED SOLUTION
Avatar of Michael Carrillo
Michael Carrillo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial