结合'like'和'equals'(mysql)

时间:2018-02-27 16:48:41

标签: mysql sql

我有这张桌子:

+------+----------+-------------+----------+
| id   | name     | name_orig   | year     |
+------+----------+-------------+----------+
|  1   | movie    | film        | 1987     |
|  2   | game     | toy         | NULL     |
|  3   | picture  | art         | 2018     |
|  4   | audio    | voice       | 1        |
+------+----------+-------------+----------+

当我使用以下内容时:

SELECT * FROM `table` WHERE `name` LIKE 'a%' OR `name_orig` LIKE 'a%' AND `year`='1'

代码获取第3行和第4行,而不只是4

我尝试使用此更改代码修复它

SELECT * FROM `table` WHERE (`name` LIKE 'a%' OR `name_orig` LIKE 'a%') AND `year`='1'

但是现在MySQL返回了一个空结果。

我如何搜索'name'和'name_orig'而不忘记'年'以获得所需的结果(第4行)?

2 个答案:

答案 0 :(得分:0)

尝试删除数字... AND year=1

周围的单引号

答案 1 :(得分:-1)

即使有一年的int我得到了第4行,我在https://www.db-fiddle.com/

上进行了测试
CREATE TABLE test (
  id INT,
  name varchar(255),
  name_orig varchar(255),
  year int
);

然后插入:

INSERT INTO test (id,name, name_orig, year)
VALUES ( 1, 'movie','film', 1987 ),(2, 'game', 'toy', NULL),(3,'picture','art', 2018),(4, 'audio', 'voice', 1)  ;

查询

SELECT * FROM `test` WHERE (`name` LIKE 'a%' OR `name_orig` LIKE 'a%') AND `year`='1'

结果:

id |    name  | name_orig | year
------------------------------------
4  |    audio | voice     |      1