简体   繁体   English

SQL通过包含字符串排序

[英]SQL sort by containing string

I am trying to sort by whether '/us/' is in a url. 我正在尝试根据网址中是否包含'/us/'进行排序。 I currently have: 我目前有:

SELECT is_live, store_url from my_table where item_id = 1306085 
ORDER BY (CASE WHEN store_url LIKE '%/us%' THEN 1 ELSE 0 END) DESC

Is there a cleaner way to do this, or is the above the only way? 有没有更清洁的方法可以做到这一点,还是只有上述方法? Conceptually, I'm looking for something a bit more readable, such as: 从概念上讲,我正在寻找更具可读性的内容,例如:

ORDER BY store_url.contains('/us/') DESC

you may try this: 您可以尝试以下方法:

SELECT is_live, store_url from my_table where item_id = 1306085 
ORDER BY instr(store_url, '/us/');

or: 要么:

SELECT is_live, store_url from my_table where item_id = 1306085 
ORDER BY instr(store_url, '/us/') > 0 ;

SQLFiddle SQLFiddle

You could create a function : 您可以创建一个函数

CREATE FUNCTION mycontains (s text, matchText VARCHAR(255))
RETURNS INT DETERMINISTIC
RETURN (CASE WHEN s LIKE CONCAT("%", matchText, "%") THEN 1 ELSE 0 END);

and use it like 并像这样使用

SELECT is_live, store_url from my_table where item_id = 1306085 
ORDER BY mycontains(store_ul, "/us/") DESC

Note: There is already a contains function, I think it works with geometric objects, that is why I named this mycontains. 注意:已经有一个包含函数,我认为它可用于几何对象,这就是为什么我将其命名为mycontains。

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

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