使用php / SQL查询数据库中的信息

时间:2016-08-01 14:25:41

标签: php mysql sql-server

database columns

我想使用这两列从表中选择数据。我想要做的是选择介于 2月和8月之间的表格和 2003年和2005年之间的年份 包括2004年和2005年1月份。我试过这个: `

$number = range(3, 8);  

foreach($number as $key=> $value):
                    $where .= " Month ='$value' AND Year BETWEEN '2003' AND '2005' or " ;                   
        endforeach;
if(strlen(trim($where)) > 0)

    $where = substr(trim($where), 0, -2);`
$query = "SELECT * FROM myTable $where";

会返回以下查询

SELECT * FROM myTable WHERE Month ='2' AND Year BETWEEN '2003' AND '2005' or Month ='3' AND Year BETWEEN '2003' AND '2005' or Month ='4' AND Year BETWEEN '2003' AND '2005' or Month ='5' AND Year BETWEEN '2003' AND '2005' or Month ='6' AND Year BETWEEN '2003' AND '2005' or Month ='7' AND Year BETWEEN '2003' AND '2005' or Month ='8' AND Year BETWEEN '2003' AND '2005'

但我查询的问题是它没有选择2004年1月和2005年1月。 谁知道如何做到这一点?

2 个答案:

答案 0 :(得分:0)

更改您的查询,如下所示..

SELECT * FROM myTable 
WHERE 
(Month ='2' AND Year BETWEEN '2003' AND '2005') 
or
( Month ='3' AND Year BETWEEN '2003' AND '2005')....

表达式中的precedence of operators determines the order of evaluation of terms。要明确覆盖此顺序和组术语,请使用括号

答案 1 :(得分:0)

SELECT * FROM myTable 
WHERE ( Month >=2 AND Month <=8 AND year BETWEEN 2003 AND 2005) OR (Month=1 AND (year=2004 OR year=2005))