简体   繁体   English

通过联接表的特定ID对mysql结果进行排序

[英]Sorting mysql result by joined table's specic IDs

I have three tables 我有三张桌子

Products 制品

id, name, desc ID,名称,描述

Flags 标志

id, name 身份证,姓名

Product_flags 产品标志

Product_id, Flag_id Product_id,Flag_id

Some Products have Flags linked to them while others not. 有些产品的标志链接到它们,而另一些则没有。 I need select products and to give preferences to specific Flags in the select query. 我需要选择产品,并在选择查询中为特定标志赋予首选项。

This is my query to give preferences to flag ids 2,3,9, followed by other flags, and followed by non-flagged products .. 这是我的查询,以优先考虑标记ID 2、3、9,其次是其他标记,然后是未标记的产品..

SELECT p.*, f.name flagname FROM products p 
LEFT JOIN products_flags pf ON pf.product_id=p.id 
LEFT JOIN flags f ON f.id = pf.flag_id
ORDER BY f.id=2, f.id=3, f.id=9, f.id, p.name

This sort order is not valid. 此排序顺序无效。 How do I get it right? 我该如何正确处理?

Thanks 谢谢

It's a strange request, but I think you might be able to get around it with a case statement in your order by clause like this: 这是一个奇怪的请求,但是我认为您可以在order by子句中使用case语句解决此问题:

SELECT 
    p.*, f.name flagname 
FROM products p 
    LEFT JOIN products_flags pf ON pf.product_id=p.id 
    LEFT JOIN flags f ON f.id = pf.flag_id
ORDER BY 
    case
        when f.id=2 then f.id-10
        when f.id=3 then f.id-10
        when f.id=9 then f.id-10
        default f.id
    end,
    p.name

Edit: A column to order by might be a good idea when you want "funky" ordering. 编辑:要进行“笨拙”排序时,按顺序排序的列可能是一个好主意。 As for the case statement, what it does is returns a value to sort by but does so in this manner - sort of like an if statement: 对于case语句,它执行的操作是返回一个要排序的值,但是这样做的方式类似于if语句:

if id=2 then treat it like -8
if id=3 then treat it like -7
if id=3 then treat it like -1
otherwise just use whatever is in id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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