在我的sql语句中排序有问题

时间:2014-10-06 22:22:24

标签: sql

我有以下sql语句,该语句效果很好,除了顺序之外,其他方式都没有像我希望的那样工作。

SELECT article_type as search
FROM appendix_article_type 
WHERE article_type LIKE '%".$keyword."%' 
ORDER BY CASE 
WHEN article_type like '".$keyword." %' THEN 0 
WHEN article_type like '".$keyword."%' THEN 1 
WHEN article_type like '% ".$keyword."%' THEN 2 
ELSE 3 END, article_type

当我输入字母V时,它会按以下顺序呈现以下内容:

//search
Volleyball - Sand
Scenic Views
Vacation Rentals
Volleyball - Indoor
Online - Delivery
Snorkeling & Diving

我希望它像这样

//search
Vacation Rentals
Volleyball - Indoor
Volleyball - Sand
Scenic Views
Online - Delivery
Snorkeling & Diving

更新/编辑:

我已经弄清楚了我的问题。我有一个联盟,我认为这会导致问题。如果我删除了工会,它工作正常。

(SELECT article_type as search, "Article Type" as search_type, "article-type" as search_page 
FROM appendix_article_type 
WHERE article_type LIKE '%v%' 
ORDER BY CASE WHEN article_type like 'v %' THEN 0 
WHEN article_type like 'v%' THEN 1 
WHEN article_type like '% v%' THEN 2 
ELSE 3 END, article_type)
UNION (
     SELECT DISTINCT(article_title) as search, "Article" as search_type, article_type_page as search_page 
     FROM system_article 
     INNER JOIN appendix_article_type ON system_article.article_type_id = appendix_article_type.article_type_id 
     WHERE article_status = '1' 
     AND article_title LIKE '%v%' 
     ORDER BY CASE WHEN article_title like 'v %' THEN 0 
     WHEN article_title like 'v%' THEN 1 
     WHEN article_title like '% v%' THEN 2 
     ELSE 3 END, article_title
) 

1 个答案:

答案 0 :(得分:1)

它在这里工作:

drop table if exists appendix_article_type;
create table appendix_article_type (article_type text);
insert into appendix_article_type values 
('Volleyball - Sand'),
('Scenic Views'),
('Vacation Rentals'),
('Volleyball - Indoor'),
('Online - Delivery'),
('Snorkeling & Diving');


SELECT article_type as search
FROM appendix_article_type 
WHERE upper(article_type) LIKE '%V%' 
ORDER BY CASE 
WHEN upper(article_type) like 'V %' THEN 0 
WHEN upper(article_type) like 'V%' THEN 1 
WHEN upper(article_type) like '% V%' THEN 2 
ELSE 3 END, article_type;

结果:

"Vacation Rentals"
"Volleyball - Indoor"
"Volleyball - Sand"
"Scenic Views"
"Online - Delivery"
"Snorkeling & Diving"

<强>更新

你必须在“工会”之外做“订购”

SELECT *
FROM
(       

  SELECT article_type as search, "Article Type" as search_type, "article-type" as search_page 
  FROM appendix_article_type 
  WHERE article_type LIKE '%v%' 

  UNION 

  SELECT article_title as search, "Article" as search_type, article_type_page as search_page 
  FROM system_article 
  INNER JOIN appendix_article_type ON system_article.article_type_id = appendix_article_type.article_type_id 
  WHERE article_status = '1' 
  AND article_title LIKE '%v%' 


) A

ORDER BY 
     CASE WHEN search like 'v %' THEN 0 
          WHEN search like 'v%' THEN 1 
          WHEN search like '% v%' THEN 2 
          ELSE 3 
     END, 
     search