jovan curayag jovan curayag - 1 month ago 6
MySQL Question

How to exclude value when selecting from database in sql

How can i exclude subject to be displayed from subject table that is already added in scheduler table? I have this code but it still shows up the subjects that are already added to scheduler table.

<?php
$sem = $_GET['semChooser'];

$res = mysql_query("SELECT * FROM scheduler WHERE semester = '$sem'") or die(mysql_errno());
$row=mysql_fetch_array($res);

$subName = $row['subject_name'];

$res1 = mysql_query("SELECT * FROM subject WHERE semester IN ('$sem', 3) AND subject_name != '$subName'") or die(mysql_errno());
while ($row=mysql_fetch_array($res1)) {

echo "
<tr class='active'>
<td align='center'>
<button type='submit' data-dismiss='modal' class='btn btn-primary btn-block btn-xs subject'><em class='fa fa-plus'></em> Add</button>
</td>
<td>".$row['subject_code']."</td>
<td>".$row['subject_name']."</td>
<td>".$row['subject_type']."</td>
<td>".$row['room_type']."</td>
<td>".$row['subject_category']."</td>
<td>".$row['year_level']."</td>
<td>".$row['units']."</td>
</tr> "; }
?>

Answer

You could use a subselect and getting the result with one query only

      SELECT * 
      FROM subject 
      WHERE semester IN ('$sem', 3)  
      AND subject_name not in ( SELECT * FROM scheduler 
                                WHERE semester = '$sem' )
Comments