如果ELSE mysql查询LIKE运算符

时间:2017-07-13 05:19:28

标签: php mysql

我有这样的mysql查询。

SELECT item FROM items WHERE catid=3 AND tag LIKE '%".$tag[1]."%' OR tag LIKE '%".$tag[2]"%' LIMIT 4

在继续搜索过程以查找具有tag LIKE '%".$tag[1]."%'的项目之前,如何告诉mysql首先搜索具有tag LIKE '%".$tag[2]."%'的项目。因为现在它看起来像mysql随机选择要执行的条件。有时它会显示4个匹配tag LIKE '%".$tag[2]."%'的结果,这是我不想要的。我希望mysql首先优先tag LIKE '%".$tag[1]."%'

4 个答案:

答案 0 :(得分:0)

您想对结果进行排序,请尝试以下

WHERE catid=3 AND `tag` LIKE '%tag%' ORDER BY IF( `tag` LIKE 'tag1%',0, IF( `tag` LIKE '%tag2', 1, 2 ) )

答案 1 :(得分:0)

使用具有tag1

限制的union可能是这样的
MariaDB [sandbox]> select * from items;
+--------+--------+--------+----------+-----------+
| ITMSTK | ITMQTY | ITMCOG | ITMURN   | ITMSOU    |
+--------+--------+--------+----------+-----------+
| WN778  | 1      |      2 | 12345112 | WEB       |
| WN776  | 1      |      1 | 12345112 | WEB       |
| WN771  | 1      |      2 | 12345112 | WEB       |
| WN845  | 1      |      1 | 22544548 | ADVERT    |
| WN846  | 1      |      1 | 22544548 | ADVERT    |
| WN845  | 1      |     20 | 44848643 | TELEPHONE |
+--------+--------+--------+----------+-----------+
6 rows in set (0.00 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> (SELECT itmsou FROM items WHERE 3=3 AND itmsou LIKE '%web%' limit 2)
    -> union all
    -> SELECT itmsou FROM items WHERE 3=3 AND itmsou LIKE '%advert%'
    -> ;
+--------+
| itmsou |
+--------+
| WEB    |
| WEB    |
| ADVERT |
| ADVERT |
+--------+
4 rows in set (0.00 sec)

答案 2 :(得分:0)

我从other post

找到答案
SELECT item FROM items WHERE catid=3 AND 
   (tag like '%".$tag[1]."%' or tag like '%".$tag[2]."%') order by case 
       when tag like '%".$tag[1]."%' then 1 
       when tag like '%".$tag[2]."%' then 2 
       else 3 
   end 
LIMIT 4

答案 3 :(得分:0)

我建议你看看下面的内容:

select *
   ,case when tag  like '%$keyword1%' then 1
        when tag   like '%$keyword2%' then 2 
    end as [priority]
from table_name
where tag   like '%$keyword1%'  or tag   like '%$keyword2%' 
order by [priority]

这实际上仍然为您提供了关键字2的结果,但同时它将关键字1优先于顶部。

或者你也许有兴趣按照"相关性"而不是你的外卡搜索。