0

I am new to MySQL and I am trying to solve a problem for a project.

I have three tables: cars, sales and customers. cars has VID as pk and some other attributes like model and price. customers has CID as pk and some attributes. sales has (VID,CID) as pk and a sales price and sales date as attributes.

The question is: "What is the model of car, that was sold most often in 2014"?

Here is my query

Select Model
From Cars,Sales
Where Cars.VID=Sales.VID
Group By Cars.VID 
Having MAX( (Select count(*)
         From Cars,Sales Where Cars.VID=Sales.VID AND SellDate Between  '2014-01-01' And '2014-12-30'));

I still get all the models, that exist in the sales table, Could tell me what is wrong?

1 Answer 1

1

First: Never use commas in the FROM clause. Always use explicit, proper, standard JOIN syntax with an appropriate ON clause.

If you want only one such model, the simplest way is ORDER BY and LIMIT:

Select c.Model
From Cars c JOIN
     Sales s
     on c.VID = s.VID
where s.SellDate >=  '2014-01-01' And
      s.SellDate < '2015-01-01'
Group By c.Model
Order by count(*) desc
limit 1;

Additional notes:

  • The columns in the GROUP BY should match the unaggregated columns in the SELECT, pretty much always.
  • Use table aliases that are abbreviations of the table names.
  • Qualify all column names, so you (and others) know where they come from.
  • Note the change in the date arithmetic. Last I heard, 2014-12-31 was in 2014 (your business rules may be different). I prefer < to between, in case the "date" column also has a time stamp.
Sign up to request clarification or add additional context in comments.

2 Comments

for what reason is the limit 1 used?
@antonisarvanitis, cause you asked in question What is the model of car and not What are the models of car

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.