使用多个 OR 语句实现 MySQL 查询。有任何最佳替代方案吗?
mysqlmysqli database
最好使用 IN() 而不是多个 OR 语句。让我们首先创建一个表 −
mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> FirstName varchar(20) -> ); Query OK, 0 rows affected (0.83 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable(FirstName) values('John'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(FirstName) values('Adam'); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable(FirstName) values('David'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable(FirstName) values('Mike'); Query OK, 1 row affected (0.48 sec) mysql> insert into DemoTable(FirstName) values('Bob'); Query OK, 1 row affected (0.09 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+----+-----------+ | Id | FirstName | +----+-----------+ | 1 | John | | 2 | Adam | | 3 | David | | 4 | Mike | | 5 | Bob | +----+-----------+ 5 rows in set (0.00 sec)
这是使用 IN() 的查询 −
mysql> select *from DemoTable where Id IN(2,3,5);
这将产生以下输出 −
+----+-----------+ | Id | FirstName | +----+-----------+ | 2 | Adam | | 3 | David | | 5 | Bob | +----+-----------+ 3 rows in set (0.00 sec)