G
G
Grigory Dikiy2017-05-21 13:06:46
MySQL
Grigory Dikiy, 2017-05-21 13:06:46

Complicated SQL query to display categories by dates?

Good day! There is a table of products:
Products
-----------------------------------
id | category_id | name | date |
----------------------------------
and category table:
Category
---------- --
id | name |
------------
Need to output:
-------------------
id | name | date |
--------------------
where name, id is taken from the category and date from the product. That is the sequence of actions:

  • Get the last 3 dates when a product was added (many products can be added on the same day)
  • Display the categories of these products, where to add the date
  • Remove duplicate fields

Started like this:
SELECT category_id, name from Products WHERE date in (SELECT dates.date FROM (SELECT date FROM Products GROUP BY date) as dates ORDER BY dates.date DESC LIMIT 3))

I got an error that you can't use LIMIT and the query is too complicated. Is it possible to simplify somehow?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2017-05-21
@frilix

Something like:

select p.id as id, p.name as P_NAME, p.date as DATE from Products p
LEFT JOIN Category c
ON c.id=p.category_id
order by p.date DESC
LIMIT 3

I
Ivan, 2017-05-21
@LiguidCool

use Join requests!!!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question