如何从列中选择所有行具有不同的值"选择全部或两者"

时间:2015-04-19 09:16:10

标签: php mysql

我在我的表中有一个名为grad_under的专栏

graduate=0
undergraduate=1

现在我只能选择毕业生或本科生,如果用户同时选择(全部)如何将两个值放在一个变量中,那么我可以同时获取毕业和本科生?

<select name="gradunder" id="gradunder">

        <option value="1">Graduate</option>
        <option value="0">Undergraduate</option>
        <option value="" selected="selected">Both</option>
      </select>

这是我用来获取行的MySQL查询。任何帮助将受到高度赞赏。

$result2 ="SELECT * FROM  curriculumcourses  
    NATURAL JOIN courses  
    WHERE  semester_ava='$avalablesemster' 
    AND curriculum_id IN (
        SELECT curriculum_id 
        FROM curriculum 
        WHERE '".$coursneededdate."' BETWEEN startdate AND enddate and grad_under='".$gradunder."')";

5 个答案:

答案 0 :(得分:1)

如果选择的选项为空(两者),则跳过上一个AND部分

$result2 ="SELECT 
  * 
FROM
  curriculumcourses NATURAL 
  JOIN courses 
WHERE semester_ava = '$avalablesemster' 
  AND curriculum_id IN 
  (SELECT 
    curriculum_id 
  FROM
    curriculum 
  WHERE '".$coursneededdate."'
   BETWEEN startdate  AND enddate ";
if(!empty($gradunder)){
 $result2 .=" AND grad_under = '".$gradunder."'";
}
 $result2 .=")";

使用JOIN代替子查询

也更好

答案 1 :(得分:1)

<?php
$str='';
if($gradunder==''){
    $str=" ('1','0') ";
}
else{
    $str=" ('".$gradunder."') ";
}
$result2 ="SELECT * FROM  curriculumcourses  "
."NATURAL JOIN courses  "
."WHERE  semester_ava='$avalablesemster' " 
."AND curriculum_id IN ( "
."  SELECT curriculum_id "
."  FROM curriculum "
."  WHERE '".$coursneededdate."' BETWEEN startdate AND enddate and grad_under IN '".$str."')";
?>

答案 2 :(得分:0)

如果只有两个值(grad或not),为什么不仅仅连接&#34;和grad_under = ...&#34;对于查询字符串,如果值不是&#39;两个&#39;?

答案 3 :(得分:0)

您需要将gradunder设置为2的值,否则它将无法通过,因为它是空白的。然后在你的php中你需要检查条件是否为2,然后根据该检查附加查询。

答案 4 :(得分:0)

if($_REQUEST['gradunder'] == ''){

$query = SELECT cu.*,c.* FROM curriculumcourses cu,courses c 

WHERE cu.curriculum_id = c.curriculum_id AND 

c.startdate<$coursneededdate AND 

c.enddate>$coursneededdate

}else{

SELECT cu.*,c.* FROM curriculumcourses cu,courses c WHERE 

cu.curriculum_id = c.curriculum_id AND

c.startdate<$coursneededdate AND 

c.enddate>$coursneededdate AND 

c.grad_under = $_REQUEST['gradunder'];

}