使用mysql根据年龄过滤成员

时间:2011-09-16 13:02:51

标签: mysql sql

我正在尝试检查某个年龄段的人。我有两个ComboBox,minagecombobox和maxagecombobox,值介于1和120之间。

我希望得到年龄介于这两个值之间的人(例如,我想过滤掉年龄在18到24岁之间的人)。

这是成员表结构:

     member_id 
     member_firstname 
     member_dob(datatype is string) (values like 1987-09-08,1976-09-08,.....)

我使用mysql作为我的数据库.....

**Modified query** 


             SELECT members.member_Id,
                   members.member_Lastname as 'Last Name',
                   members.member_Firstname as 'First Name',
                   members.member_Postcode as 'Post Code',
                   members.member_Reference as Reference,
                   members.member_CardNum as 'Card Number',
                   members.member_IsBiometric as Biometric,
                   members.member_DOB as DoB,
                   mshiptypes.mshipType_Name as Membership,
                   mshipstatustypes.mshipStatusType_Name as Status,
                   membertomships.memberToMship_EndDate as Expiry
                     FROM members
    INNER JOIN membertomships ON membertomships.member_Id = members.member_Id
     INNER JOIN mshipoptions ON mshipoptions.mshipOption_Id = membertomships.mshipOption_Id
    INNER JOIN mshiptypes ON mshiptypes.mshipType_Id = mshipoptions.mshipType_Id
    INNER JOIN mshipstatustypes ON mshipStatusTypes.mshipStatusType_Id = membertomships.mshipStatusType_Id
    WHERE memberToMship_EndDate BETWEEN '2011-09-24' AND '2011-09-30'
    AND members.member_active LIKE 'y%'
    AND (YEAR(CURDATE(members.member_Dob))-YEAR()) - (RIGHT(CURDATE(),5)< RIGHT(member_Dob,5)) BETWEEN '21' AND '102'
    ORDER BY members.member_Lastname

有这样的错误......

     Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'member_Dob))-YEAR()) - (RIGHT(CURDATE(),5)< RIGHT(member_Dob,5)) BETWEEN '21' AN' at line 19

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT * FROM MEMBER
WHERE (YEAR(CURDATE())-YEAR(member_dob)) - (RIGHT(CURDATE(),5)<RIGHT(member_dob,5)) 
BETWEEN 18 AND 24

WHERE子句具有年龄计算公式。通过从当前年份减去出生年份获得年数,然后如果当前日期和月份少于DOB的日期和月份,则进一步减去1。如果您遇到数据类型不匹配错误,请使用STR_TO_DATE(member_dob, '%Y-%M-%d')将字符串DOB转换为DATETIME DOB。

答案 1 :(得分:1)

不完全确定你要做什么。你的问题没有多大意义,因为组合框不是mySQL,它们是你用来与数据库交互的任何语言。您可以更好地以编程方式确定日期范围并将动态变量传递给mySQL,但现在这是一个概念。另外,为什么member_dob是一个字符串?把它变成日期时间......

SELECT * FROM Member 
WHERE STR_TO_DATE(member_dob, '%Y-%M-%d') BETWEEN '1900-0916' AND CURDATE()

答案 2 :(得分:0)

重构以使member_dob的类型为DATE(或其他与日期相关的数据类型),然后使用SELECT member_id, member_firstname, member_dob FROM Member WHERE member_dob BETWEEN '1993-09-16' AND '1987-09-16'(请注意1993 == 2011-18,1987 == 2011- 24,月和日都是从今天起。)

你需要将出生日期转换为某种日期 - 这种方法允许你使用数据库进行数据搜索,这是非常擅长的(而不仅仅是使用它)作为数据商店)。