Robert Ursărescu
Robert Ursărescu

Reputation: 81

How can I order query by another table?

I have a long query, but I keep it simplified:

$query = $this->db->query(" SELECT id FROM oc_products ORDER BY ...? ");

Here is the problem. In this table I have all the products, but I have a second table, oc_seller_products, where I have same column ID, which match with oc_products. I want to be ordered first id's which dont appear in oc_seller_products, and at last, appear id's which appear in oc_seller_products.

For example: in oc_products I have ID: 1,2,3,4,5

In oc_seller_products I have only ID: 4

I need to be ordered like this: 5,3,2,1 and the last: 4

I have a marketplace, so I want first my products to appear, on category page, then my sellers products.

I really have no idea how to do that.

Upvotes: 1

Views: 28

Answers (1)

ysth
ysth

Reputation: 98388

select op.id
from oc_products op
left join oc_seller_products osp using (id)
order by osp.id is null desc, op.id desc

osp.id is null will be 1 when there is not an oc_seller_products record and 0 when there is, so sort by that, descending, first. And then after that, within those two categories, you seem to want descending id order.

Upvotes: 4

Related Questions