从表中选择另一个表中的行不匹配

时间:2013-11-13 10:18:59

标签: php mysql sql

我有两张桌子:

  1. 客户
  2. customer_communication
  3. customer表具有唯一的sequence列,customer_communication表的customer_seq与customer表中的sequence列匹配。

    customer_communication表中的行有一个datetime列,我使用这些查询从两个表中选择数据:

    echo '<table width="100%" border="0" cellspacing="10" cellpadding="10">';
        //select from the customer_communication table
        $sql="SELECT * from customer where company_status = '' and no_communication = '' order by company ASC ";
        $rs=mysql_query($sql,$conn);
        while($result=mysql_fetch_array($rs))
        {
            $sql2="SELECT * from customer_communication WHERE customer_seq = '".$result["sequence"]."' and datetime > DATE_ADD(DATE(now()), INTERVAL 15 DAY) order by datetime ASC ";
            $rs2=mysql_query($sql2,$conn);
            if(mysql_num_rows($rs2) > 0)
            {
                echo '<tr>
                <td><a href="customer_communication.php?seq='.$result["sequence"].'">'.$result["company"].'</a></td>
                </tr>';
            }
        }
        echo '</table>';
    

    所以它选择customer表中的所有行,然后从customer_communication表中选择customer_seq = sequence并且距datetime列15天的行。

    如何显示customer_communication表中不存在的customer表中的所有行

    例如,客户中有序列1,这在customer_communication表的customer_seq列中不存在,所以我想显示这个

3 个答案:

答案 0 :(得分:1)

这可以通过基本SQL来完成。我会留给你把它整合到你的php中。

SELECT * FROM Customer c
WHERE NOT EXISTS
    (SELECT * FROM Customer_Communication
    WHERE Customer_seq = c.Customer_Seq);

答案 1 :(得分:0)

你能试试吗,

$sql="SELECT * FROM customer as a, customer_communication as b  WHERE a.company_status = '' AND a.no_communication = '' AND b.customer_seq NOT IN ( SELECT sequence FROM customer ) AND b.datetime > DATE_ADD(DATE(now()), INTERVAL 15 DAY) ORDER BY a.company ASC ";

答案 2 :(得分:0)

有多种不同的方法可以执行此操作,但一种方法是使用子查询从customer_communication表中获取唯一的customer_seq值,然后从customer表中检索不具有sequence列的值的所有行。

Select * from customer c
where c.sequence not in 
(select distinct customer_seq from customer_communication)