mysql:选择使用like运算符并按列名对结果进行排序

时间:2016-01-11 12:28:17

标签: php mysql sql

$qry="SELECT * 
      FROM `tbl_postad` 
      WHERE category LIKE '% $car %'
        OR title LIKE '% $car %' 
        OR text LIKE '% $car %'";

编辑:抱歉错过了$。语法错误 - 好的

 id category title description   
  1    car 
  2    car
  3            car
  4            car
  5            car
  6                    car


?>

但我希望输出首先按类别列出行,然后是标题,然后是描述。 有没有使用工会 提前致谢。

示例:

prePersist

3 个答案:

答案 0 :(得分:2)

ORDER BY CASE WHEN category LIKE '% $car %' THEN 0
              WHEN title LIKE '% $car %' THEN 1
              WHEN description LIKE '% $car %' THEN 2
         END

答案 1 :(得分:2)

您可以尝试如下:

SELECT * 
FROM `tbl_postad` 
WHERE category LIKE '%car%' OR title LIKE '%car%' OR description LIKE '%car%'
ORDER BY (category LIKE '%car%') DESC,
     (title LIKE '%car%') DESC,
     (description LIKE '%car%') DESC;

答案 2 :(得分:1)

您可以使用like as =`:

进行同样的思考
SELECT * 
FROM `tbl_postad` 
WHERE category LIKE '% car %' OR title LIKE '% car %' OR text LIKE '% car %'
ORDER BY (category LIKE '% car %') DESC,
         (title LIKE '% car %') DESC,
         (text LIKE '% car %') DESC;

根据您的示例数据,我假设您打算OR而不是AND