Thursday, 30 August 2018

Ask to have all the elements of a table but command by another table that does not have all the elements

I have one table products with id of product and name.

Second table is products_last_usage where I keep product_iduser_id and last_used_at.
Whenever a user clicks on a product, I have the field last_used_at updated.
Now, I need a query to list all products, and order them first by last_used_at, and then by name of product. It has to be PER USER. i.e. every user will have his own order of the table.
But I need all products, even if there are no records of them in the second table.
How to do that?
You can help me with a rails query or mysql query.

You can use a left join:
select p.*
from products p left join
     products_last_usage plu
     on plu.product_id = p.id and plu.user_id = $user_id
order by (last_used_at is not null) desc, last_used_at desc;

Ordering by last_used_at desc should also work. However, I think it is clearer to explicitly handle NULL values.

0 comments:

Post a Comment