简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM