简体   繁体   English

如何通过另一个表对查询进行排序?

[英]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.

相关问题 如何根据分片ID通过另一个表的计数来排序SQL查询的结果? - How can I order the results of an SQL query by the count of another table based on a shard ID? 如何在另一个表中执行的mysql查询中添加条件? - how can i add condition in mysql query executed in another table? 如何通过另一个相关的表Yii CDbCriteria过滤查询? - How can i filter query by another related table Yii CDbCriteria? 如何从一个表中检索信息以订购另一个表的结果 - How can I retrieve information from one table to order the results of another MySQL-如何根据另一个表中的列排序 - MySQL - How do I order based on columns from another table PHP / SQL如何使查询包含另一个表中没有记录的结果? - PHP/SQL How can I make my query include results that has no records in another table yet? 如果返回 True mysql php,如何查询唯一值并更新同一表中的另一个字段 - How Can I Query for Unique Value and Update another Field in Same Table If return True mysql php 如何将这些查询与另一个父表中的 where 子句组合成单个查询? - How can i combine these queries into single query with where clause from another parent table? 我可以按另一个表中的记录数对SQL查询的结果进行排序吗? - Can I sort results of SQL query by the number of records in another table? 如何通过另一个查询订购MYSQL查询? - How to order a MYSQL query by another query?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM