我正在尝试实施搜索功能,用户可以搜索以下任一项:姓名,年龄,地址,性别,课程和年份?
SELECT *
FROM student
WHERE name LIKE '%name%'
OR age BETWEEN 'age' AND 'age'
OR address LIKE '%address%'
OR gender = 'gender'
OR course LIKE '%course%'
OR YEAR = 'year'
Note: each of the search criteria is in different input field
但是当用户输入一个或多个搜索条件时,我无法获得正确的结果。
我知道何时使用OR
和AND
,但我无法为此编写查询的正确方法。
例子是:我有桌上学生。
id name address age gender course year
2 juan New York 19 male IT 2
4 whitney New Jersey 23 female BA 4
7 manny Canada 20 male Law 2
Note: age is a select input field. example is
15-20
20-25
25-30 and etc.
然而,当我尝试搜索示例是IT
的课程时,它会返回所有错误的记录。正确的结果应该只与IT
相关,就像第一条记录一样。
答案 0 :(得分:0)
我认为这就是你想要的
SELECT * FROM student WHERE name LIKE '%name%' OR (age > 23 AND age < 30)
OR address LIKE '%address%' OR gender = 'gender' OR course LIKE '%course%'
OR YEAR = 'year'