0

I have been learning how to use nested joins but I can't seem to get them working for my current database.

I have created these tables: enter image description here

I want to first find out how many users have made at least one usage (they have some minutes in their account), created their account in 2016, and used an iPhone in 2013. I've tried which is producing an error:

SELECT COUNT(user_id) FROM USER
WHERE usage_count > 0
AND account_created <= ‘2016-12-31’
AND account_created >= ‘2016-01-01’
INNER JOIN PRODUCT
WHERE product = 'iPhone';
7
  • INNER JOIN PRODUCT ------ you're missing the columns to join ON Commented Dec 23, 2016 at 2:50
  • JOIN clauses have to go before WHERE. Commented Dec 23, 2016 at 2:51
  • There's no usage_count column in any of your tables, so what is usage_count > 0 supposed to refer to? Commented Dec 23, 2016 at 2:53
  • @Barmar usage_count is in the user table Commented Dec 23, 2016 at 2:56
  • Oops, missed that. It would be better if you posted text instead of images, so we can use the browser's search function. Commented Dec 23, 2016 at 2:57

1 Answer 1

1

Your query error out which is expected since you have two WHERE clause and USER is key word and shouldn't be used as identifier. I have escaped them using backtique better use a non key/reserve word as your column name. Your query should look like

SELECT COUNT(u.user_id) FROM `USER` u
INNER JOIN USAGE us on us.user_id = u.user_id
JOIN PRODUCT p ON us.product_id = p.product_id
WHERE p.product = 'iPhone'
AND u.usage_count > 0
AND u.account_created <= '2016-12-31'
AND u.account_created >= '2016-01-01'
Sign up to request clarification or add additional context in comments.

8 Comments

USER is a keyword, but it's not reserved, so it doesn't need to be escaped.
You need to join with the usage table, since that's what links user and product.
You've got the wrong types of quotes around the dates (because you copied them from the question).
@Barmar, yes right it's key word. Change the wording in answer. Again I have just suggested the flaws in his posted query and not the actual query that would work.
MySQL has so many keywords that are common words, it's hard to avoid using them as table and column names. E.g. everyone has a column named password.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.