如果2列不匹配,mysql查找不匹配的记录

时间:2014-01-23 06:27:45

标签: php mysql

我试图从2个表中找到无法比拟的记录我在下面尝试查询它工作正常但我需要找到多列匹配PLZ帮助

res = mysql_query("SELECT * FROM emp WHERE emp.roll_no NOT IN (SELECT emp_no FROM emp_old)");

同样我做了如下.. 它有错误..

emprollnoname

emp_oldemp_noname

我需要找出这两个无与伦比的列

res = mysql_query("SELECT * FROM emp WHERE emp.roll_no AND emp.name NOT IN (SELECT emp_no AND name FROM emp_old)"); 

2 个答案:

答案 0 :(得分:0)

您可以尝试使用NOT EXISTS

SELECT 
  * 
FROM
  emp e 
WHERE NOT EXISTS 
  (SELECT 
    1 
  FROM
    emp_old 
  WHERE emp_no = e.emp.roll_no)

或只是

SELECT 
  * 
FROM
  emp  
WHERE NOT EXISTS 
  (SELECT 
    1 
  FROM
    emp_old 
  )

编辑我在查询中添加了另一列颜色,如果不匹配则会为您显示红色,为匹配的员工提供绿色

SELECT *
,(CASE WHEN eo.emp_no IS NULL THEN 'red' ELSE 'green') color
 FROM emp e
LEFT JOIN emp_old eo ON (e.roll_no = eo.emp_no)

<强>突出显示

while($row=mysql_fetch_array($res)) {
echo "<tr>"; echo "<td align='center' width='200'><span style='background-color:red;'>" . $row['emp_no'] . "</span></td>";
echo "<td align='left' width='200'><span style='background-color:red;'>" . $row['name'] . "</span></td>"; echo "</tr>";
}
echo "</table>";

Subqueries with EXISTS or NOT EXISTS

答案 1 :(得分:0)

使用JOIN而不是子查询

尝试此操作
SELECT e.* 
FROM   emp e 
LEFT JOIN emp_old eo 
ON e.rollno = eo.emp_no AND e.name = eo.name
WHERE eo.emp_no IS NULL AND eo.name IS NULL;

请查看sqlfiddle