2013-03-22 29 views
4

以下是我的MySQL表。我想从我的表hello中选择一个特定范围的值。如何在MySQL表中选择特定范围的值?

name  age  job  gender 

A   33   dgfd  m 
b   44   gdfg  f 
c   21   jhkh  m 
e   23   etertr m 

我该如何选择年龄属于20-30岁年龄段的男性。

SELECT hello.* 
WHERE hello.age='20-30' AND hello.gender='m'; 
+0

可能重复(http://stackoverflow.com/questions/12794991/select-rows-with-in-particular-range-sql-query) – JNK 2013-03-22 15:44:44

+0

I”已经用年龄计算增加了一个例子。 – 2013-03-22 17:19:18

回答

13

您可以使用WHERE子句来过滤数据:

select name, age, job, gender 
from hello 
where age >=20 
    and age <=30 
    and gender = 'm' 

SQL Fiddle with Demo

这也可以使用BETWEEN写成:

select name, age, job, gender 
from hello 
where age between 20 and 30 
    and gender = 'm' 

SQL Fiddle with Demo

通常情况下,您需要存储一个人的出生日期而不是age,然后可以在需要时计算年龄。

11
SELECT name 
FROM hello 
WHERE age BETWEEN 20 AND 30 
    AND gender = 'm' 

不要存储age。存储日期字段并计算年龄。如果这个人长大了会发生什么?

+1

我想检查年龄和性别,而不是名称。 – Ameer 2013-03-22 15:37:03

+1

@Ameer您的陈述让您感到困惑,您希望'c'和'e' – Kermit 2013-03-22 15:44:56

+0

现在可以编辑... :) – Ameer 2013-03-22 16:04:02

0

SELECT * FROM hello WHERE age>=20 AND age <=30 AND gender='m';

0

因为年龄从去年到今年改变你可以做到这一点。

设置表是这样的:

delimiter $$ 

CREATE TABLE `hello` (
    `name` varchar(45) NOT NULL, 
    `birthdate` date DEFAULT NULL, 
    `job` varchar(45) DEFAULT NULL, 
    `gender` enum('m','f') DEFAULT NULL, 
    PRIMARY KEY (`name`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8$$ 

价值观我用:

'A', '1980-08-04', 'clerk', 'm' 
'B', '1969-10-12', 'waitress', 'f' 
'C', '1992-09-16', 'pilot', 'm' 
'd', '1991-02-21', 'unemployed', 'm' 

SQL查询:

select name,TIMESTAMPDIFF(YEAR,birthdate,current_date) as age,job,gender from hello where birthdate > current_date - interval 30 YEAR and birthdate < current_date - interval 20 year; 

返回答案,查询

name age  job   gender 
C  20  pilot  m 
d  22  unemployed m 

在此处添加到SQLFiddle。 http://www.sqlfiddle.com/#!2/0143c/1/0

的[选择的行与在特定范围内的SQL查询]