【发布时间】:2015-09-30 18:36:17
【问题描述】:
鉴于这个模型:
+-----------+-------------+---------------------------+
| item_id | item_name | desc |
+-----------+-------------+---------------------------+
| 1 | Product 1 | lorem ipsum dolor... |
| 2 | Product 2 | lorem mauris eu... |
| 3 | Product 3 | scelerisque sagittis... |
| 4 | Product 4 | lorem dolor ipsum... |
| 5 | Product 5 | ipsum dolor lorem... |
+-----------+-------------+---------------------------+
我想搜索在item_name 或desc 中包含单词lorem ipsum 的所有产品。此外,lorem 和 ipsum 之间可以出现任何单词,lorem 和 ipsum 可以按任何顺序出现。基本上,此搜索将返回项目 1、4 和 5
现在,我知道我可以做到这一点:
SELECT * FROM items
WHERE (item_name LIKE 'lorem%ipsum'
OR desc LIKE 'lorem%ipsum')
OR (item_name LIKE 'ipsum%lorem'
OR desc LIKE 'ipsum%lorem')
但如果我的搜索词更长(即 lorem ipsum dolor sit amet、consectetur adipiscing elit),我觉得在查询中添加 OR 的数量可能会变得有点荒谬。有没有更简单/更有效的方法来处理这个问题?
【问题讨论】:
-
你可以试试
WHERE (item_name like '%lorem%' and item_name like '%ipsum%') OR (desc like '%lorem%' and desc like '%ipsum%')。这需要所有搜索字词,但顺序不限,在任一列中。