Home  >  Article  >  Backend Development  >  mysql如何根据字符串中的字母查询出一个字段中与字母相匹配的数据

mysql如何根据字符串中的字母查询出一个字段中与字母相匹配的数据

WBOY
WBOYOriginal
2016-06-20 12:28:13964browse

如:
一个字符串可能为A,B,C
也可能为B,C
也可能为C

数据表中fID字段存在多个A或B或C

如果字符中包含A,B,C,要查询出fID中fID为A或B或C的数据
如果字符中包含,B,C,要查询出fID中fID为B或C的数据

CREATE TABLE `tab` (
`fID` VARCHAR(2) NULL DEFAULT NULL,
`fName` VARCHAR(10) NULL
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
INSERT INTO `tab` (`fID`, `fName`) VALUES
('A', 'A01'),
('A', 'A02'),
('A', 'A03'),
('A', 'A04'),
('B', 'B02'),
('B', 'B03'),
('B', 'B04'),
('B', 'B01'),
('B', 'B05'),
('C', 'C02'),
('C', 'C03'),
('C', 'C01');


回复讨论(解决方案)

假定你输入的串是(或经处理后)A,C,B 这样的格式,那么可以
严格匹配
select * from tab where find_in_set(fID, '$inp')
模糊匹配
select * from tab where '$inp' like concat('%‘, fID, '%')

感谢用xuzuning 的解答,用 find_in_set(fID, '$inp')解决了

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