简体   繁体   English

基于SQL查询的订单结果

[英]Order results based on SQL query

I currently query a table for items with a certain category . 我目前在表中查询具有特定category项目。 I have extended this query to also looks within the item description column too. 我已将此查询扩展为也可以在项目description列中查找。 My question is, how do i order results so that the category matches are first and the description is last? 我的问题是,如何排序结果,以便category匹配为第一,描述为最后?

`SELECT * FROM myTable WHERE `category` LIKE '%keyword%' || `description` LIKE '%keyword%'

In my above query simply adding a ORDER BY category will not suffice. 在我上面的查询中,仅添加ORDER BY category不够的。 The only way I can think of doing this is two separate queries with two separate result variables. 我能想到的唯一方法是两个单独的查询以及两个单独的结果变量。

I'm using php and mysqli 我正在使用phpmysqli

It could be done like this 可以这样做

SELECT *
FROM myTable
WHERE `category` LIKE '%keyword%' || `description` LIKE '%keyword%'
ORDER BY
    CASE
      WHEN `category` LIKE '%keyword%' THEN 1
      WHEN `description` LIKE '%keyword%' THEN 0
END 

It could be done like this 可以这样做

SELECT *
FROM myTable
WHERE `category` LIKE '%keyword%' || `description` LIKE '%keyword%'
ORDER BY
    CASE
      WHEN `category` LIKE '%keyword%' THEN 1
      ELSE 0
    END CASE
      DESC

If you would like to broaden that SQL query and preserve these ordering, you can utilize: 如果您想扩展该SQL查询并保留这些顺序,则可以利用:

SELECT *
FROM myTable
WHERE `category` LIKE '%keyword%' || `description` LIKE '%keyword%'
ORDER BY
    CASE
      WHEN `category` LIKE '%keyword%' THEN 1
      ELSE 0
    END CASE
      DESC,
    CASE
      WHEN `description` LIKE '%keyword%' THEN 1
      ELSE 0
    END CASE
      DESC

Results, what are both description results and category results, will be on begin - as it was not specified, I suppose, that so it is requested or accepted. 结果(既是description结果又是category结果)将在开始时显示-我想这是未指定的, 因此是请求或接受的结果。

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

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