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
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?
MySQL Server

Avatar of undefined
Last Comment
Michael Carrillo

8/22/2022 - Mon
Michael Carrillo

Your not joining your tables correctly. But to provide the correct syntax, I need to know are you using MySQL or SQL Server?
Michael Carrillo

If you have SQL Server you can try:

SELECT COUNT (shop_id) AS total_shops
FROM shops
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
x.sex=0 AND
(p.date >= (SELECT
prior_login FROM
users WHERE
user_id = 22)  ) )

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.)
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck

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.
Michael Carrillo

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question