[英]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.
在此表中,我有所有产品,但我有第二个表 oc_seller_products,其中我有相同的列 ID,与 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.
我想订购第一个没有出现在 oc_seller_products 中的 id,最后是出现在 oc_seller_products 中的 id。
For example: in oc_products I have ID: 1,2,3,4,5例如:在 oc_products 中我有 ID:1,2,3,4,5
In oc_seller_products I have only ID: 4在 oc_seller_products 我只有 ID:4
I need to be ordered like this: 5,3,2,1 and the last: 4我需要这样排序:5,3,2,1 最后一个: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. osp.id is null
当没有oc_seller_products 记录时将为 1,当有时为 0,因此首先按降序排序。 And then after that, within those two categories, you seem to want descending id order.然后在那之后,在这两个类别中,您似乎想要降序 id 顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.