dongluobei9359 2012-05-02 00:50
浏览 26
已采纳

PHP / MySQL排序项首先如果“word”存在,那么其余的ASC?

I have a food database and I'm trying to implement a simple search that would put first items that are "raw" or "least processed".

For example, when I'm searching for "carrot", I really don't want to have to sort through all the processed food (carrot cake, etc), fast food (Wendy's carrot big mac, etc). I want the first items to be "carrots, raw", "carrot, boiled", "carrot frozen", "carrot, canned", etc.

Is there a way to do that in MYSQL so that I sort my items by "presence of keyword" first (let's say : "raw", "fresh", "boiled", "frozen"...) and then all other occurrences after?

Note :

  • the keyword may or may not be present
  • the keyword may be anywhere
  • I must also find the search keyword alone, in this example "carrot" so that "carrot cake" is still in my results.

Thanks a lot!

Joel

  • 写回答

3条回答 默认 最新

  • dtziv24262 2012-05-02 00:55
    关注

    This might work for you:

    SELECT * FROM foods
    WHERE foods.title LIKE '%carrot%'
    ORDER BY foods.title LIKE '%raw%' DESC, foods.title
    

    The reason it's DESC is because that will return 0 or 1, and you want the results that returned 1 to be sorted first.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类