Home  >  Article  >  Database  >  【当心!】多个like查询会出现大量重复数据

【当心!】多个like查询会出现大量重复数据

WBOY
WBOYOriginal
2016-06-07 14:55:021621browse

多个like查询会出现大量重复数据 无 ===============================问题描述===================================两个表表usersid username1 andy2 jack3 leo4 kimi表carid title userid chnname1 bmw750 1 宝马2 bmw530 1 宝马3 bmw 2 宝马4 benzc2 1 奔驰

多个like查询会出现大量重复数据
===============================问题描述===================================
两个表
表users
id username
1 andy
2 jack
3 leo
4 kimi
表car
id title userid chnname
1 bmw750 1 宝马
2 bmw530 1 宝马
3 bmw 2 宝马
4 benzc2 1 奔驰
5 benzE3 2 奔驰
SQL:select * from a.*,b.* from car a inner join username b on a.userid = b.id
现在需要增加like查询条件 查询title类似于bmw的
select * from a.*,b.* from car a inner join username b on a.userid = b.id and a.title like '%bmw%'
这个语句会得到三条结果。正确的。但如果我再加上一个like条件就不行
查询title类似于bmw chnname类似于宝马
select * from a.*,b.* from car a inner join username b on a.userid = b.id and a.title like '%bmw%' or a.chnname like '%宝马%'
这样的话会得到一大堆的重复数据
==============================分析=================================
之所以会得到那么多重复数据是因为上面的SQL相当于
select a.*,b.* 
from car a 
inner join username b 
on a.userid = b.id AND a.title like '%bmw%'
UNION ALL
select a.*,b.* 
from car a 
inner join username b 
on a.chnname like '%宝马%'
===============================解决=================================
在like条件中加()或者使用where
1.select * from a.*,b.* from car a inner join username b on a.userid = b.id and 
(a.title like '%bmw%' or a.chnname like '%宝马%')
2.select a.*,b.* from car a inner join username b on a.userid = b.id 
where a.title like '%bmw%' or a.chnname like '%宝马%'
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn