按部分关键字匹配排序

时间:2013-08-17 20:51:13

标签: mysql

我有以下查询:

SELECT 
        *
    FROM
        `Magic The Gathering`
    WHERE
        `set` =  'Magic 2013'
    ORDER BY
        FIELD (`rarity`, 'Mythic', 'Rare', 'Uncommon', 'Common', 'Land') ASC,
        FIELD (`type`, 'Planeswalker ', 'Creature', 'Instant', 'Sorcery', 'Enchantment', 'Artifact', 'Land') ASC
    LIMIT
        500

'Type'包含各种关键词,如'Planeswalker - Ajani','Legendary Artifact','Creature - Elf Druid'等。

如何根据部分匹配的关键字对类型进行排序,例如“Planeswalker”,“Creature”,“Instant”,“Sorcery”,“Enchantment”,“Artifact”,“Land”?

2 个答案:

答案 0 :(得分:0)

您可以使用案例陈述来执行此操作,例如:

Order by (case when type like '%Planeswalker%' then 1
            When ....
        end)

答案 1 :(得分:0)

您可以使用CASE WHEN来解决您的问题。

SELECT 
        *
    FROM
        `Magic The Gathering`
    WHERE
        `set` =  'Magic 2013'
    ORDER BY
        FIELD (`rarity`, 'Mythic', 'Rare', 'Uncommon', 'Common', 'Land') ASC,
        CASE
            WHEN `type` LIKE '%Planeswalker%' THEN 1
            WHEN `type` LIKE '%Creature%' THEN 2
            WHEN `type` LIKE '%Instant%' THEN 3
            -- ...

        END CASE
    LIMIT
        500