SQL使用LIKE%?%搜索多列 [英] SQL search multiple columns using LIKE %?%

查看:325
本文介绍了SQL使用LIKE%?%搜索多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户数据库,其中的列为 first_name, last_name和 '电子邮件



然后我尝试使用 SQL 进行搜索,如下所示:

  SELECT * 
来自客户
电子邮件喜欢的%?%或
个名字喜欢的%? %OR
last_name LIKE%?%;

所以说我数据库中的数据这些列是这样的:

 表tr td {
padding:5px;
}

< table border = 1>
< tr>< td> first_name< / td>< td> last_name< / td>< td> email< / td> ; / tr>
< td> test< / td> td> user< / td< td> user@test.com< / td< / tr>
< / table>

在这种情况下,我可以搜索为'test'进行搜索,或者我可以搜索'user'并获得正确的结果,但是如果我搜索测试用户 没有结果。



跨多列搜索的最佳方法是什么像这样,其中搜索字符串的仅一部分可能在一个列中,而另一列中的一部分。

解决方案

您需要一个不同的查询。无法用多个输入参数表示 Like



因此,您可以输入所有搜索词进入表格,沿着这些行...

  SELECT 
*
FROM
个客户
内部联接

选择'%test%'AS参数
UNION ALL SELECT'%user%'

AS搜索
ON customer.email像LIKE search.param
或customers.first_name LIKE search.param
或客户p>

(或者您可以制作一个实际的表而不使用内联视图。)


I have a database of users with columns first_name', 'last_name' & 'email.

I am then trying to search using SQL like so:

SELECT * 
FROM customers 
WHERE email LIKE %?% OR 
      first_name LIKE %?% OR 
      last_name LIKE %?%";

So say my data in my database for those columns is this:

table tr td{
  padding:5px;
}

<table border="1">
<tr><td>first_name</td><td>last_name</td><td>email</td></tr>
<tr><td>test</td><td>user</td><td>user@test.com</td></tr>
</table>

In this case I can search for 'test' or I can search for 'user' and get the correct result but if I search for 'test user' there is no results.

What is the best way to go about searching across multiple columns like this where only part of the search string might be in one column and part in another column.

解决方案

You need a different query. There is no way to express LIKE with multiple input parameters.

So, you could put all of your search terms in to a table, something along these lines...

SELECT
  *
FROM
  customers
INNER JOIN
(
            SELECT '%test%'   AS param
  UNION ALL SELECT '%user%'
)
  AS search
    ON customers.email      LIKE search.param
    OR customers.first_name LIKE search.param
    OR customers.last_name  LIKE search.param

(Or you could make an actual table instead of using an inline view.)

这篇关于SQL使用LIKE%?%搜索多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆