在工作中遇到的一些关于Sql查询的问题整理记录,实现环境 SQLService 2014
一、对同一个字段,多个关键词的查询几种实现方式
基本语法:
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
案例表(TbUser):
Id | LastName | FirstName |
---|---|---|
1 | Adams | John |
2 | Bush | George |
3 | Carter | Thomas |
查询语句实现:
1、单个关键词模糊查询
SELECT * FROM TbUser WHERE LastName LIKE "%d%"
2、多个关键词查询
实现一:SELECT *
FROM TbUser
WHERE LastName like "%d%" or LastName LIKE "%e%" or LastName LIKE "%d%"
实现二:SELECT TbUser.LastName,temp.m
FROMTbUser,(values("%a%"),("%b%"),("%c%")) as temp(m)
FROM TbUser.LastName LIKE temp.m
实现三: SELECT LastName
FROM TbUser
WHERE LastName LIKE any(array["%a%","%b%","%e%"])
实现四:SELECT LastName
FROM TbUser
WHERE LastName LIKE "%[a|b|e]%’
二、sql中In关键词的变相实现
当匹配数据数据比较多的时候,In需要逐一比对,效率低下,构造LEFT JOIN 结构会比较大的提高效率。
语法:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)
实现一:
SELECT *
FROM TbUser
WHERE Id in (1,2,3,4)
实现二、
SELECT x FROM TbUser u
LEFT JOIN TbDetails as d on u.Id=d.FkUserId
WHERE d.FkUserId is not null
实现三:
如果又一个数组需要进行In查询,可以如下实现,构造临时表进行Inner join 查询
SELECT u.*
FROM bUser u
INNER JOIN ( VALUES("a"),("b"),("c"),("d"),("e") ) as temp(m) ON u.LastName=temp.m