如何根据mysql中另一个表的结果从一个表中获取内容

时间:2013-11-18 10:19:18

标签: php mysql sql

我有两个mysql表,其中一个内容称为请愿书

{"success":1,"petitions":[{"id":"6","name":"should he go","timestamp":"2013-10-26 03:02:44"},{"id":"3","name":"Olara Otunu should get married","timestamp":"2013-10-24 14:33:53"},{"id":"4","name":"Teachers deserve 30 not 20 salary rise","timestamp":"2013-10-24 14:33:53"},{"id":"5","name":"Prostitution should be banned","timestamp":"2013-10-24 14:33:53"},{"id":"1","name":"Has Jennifer Musisi done great work for Kampala","timestamp":"2013-10-24 14:32:58"},{"id":"2","name":"Do lecturers deserve 100% salary increase","timestamp":"2013-10-24 14:32:58"}]} 

,另一个表名为petition_response

{"success":1,"petition_response":[{"id":"2","petitionID":"2","yes":"0","no":"1","memberID":"14","timestamp":"2013-11-02 08:36:20"},{"id":"1","petitionID":"1","yes":"1","no":"0","memberID":"14","timestamp":"2013-11-01 21:26:02"}]}

我需要选择在petition_response中没有回复的请愿书。但是如果他们在petition_response表中有任何响应,那么memberID不应该等于14

我在下面尝试过这段代码,但它无效

$result = mysql_query("select * from petition_response where memberID='14' order by timestamp DESC", $db->connect());
while($row = mysql_fetch_assoc($result)){
    $id = $row['id'];

    $result2 = mysql_query("select * from petitions where id != '$id' order by timestamp DESC", $db->connect());            
}
return $result2;

2 个答案:

答案 0 :(得分:0)

$query = "
SELECT * 
  FROM petition_response pr
  LEFT
  JOIN petitions p
    ON p.id = pr.id
 WHERE pr.memberID = 14 
   AND p.id IS NULL
 ORDER
    BY pr.timestamp DESC;
";

答案 1 :(得分:0)

您希望实现反连接,在MySQL中有三种可能性:

  1. 使用NOT IN

    SELECT *
    FROM   petitions
    WHERE  id NOT IN (
             SELECT petitionID
             FROM   petition_response
             WHERE  memberID = 14
           )
    
  2. 使用NOT EXISTS

    SELECT *
    FROM   petitions p
    WHERE  NOT EXISTS (
             SELECT *
             FROM   petition_response r
             WHERE  r.petitionID = p.id
                AND r.memberID   = 14
             LIMIT  1
           )
    
  3. 使用OUTER JOIN

    SELECT p.*
    FROM   petitions p
             LEFT OUTER JOIN petition_response r
                          ON r.petitionID = p.id AND r.memberID = 14
    WHERE  r.petitionID IS NULL
    
  4. sqlfiddle上查看。

    根据@Quassnoi's analysis

      

    摘要

         

    MySQL可以优化所有三种方法来进行NESTED LOOPS ANTI JOIN

         

    它将从t_left中获取每个值,并在t_right.value的索引中查找。如果索引命中或索引未命中,相应的谓词将分别立即返回FALSETRUE,并且将立即从t_left返回行的决定而不检查t_right中的其他行。

         

    然而,这三种方法生成三个不同的计划,由三个不同的代码执行。执行EXISTS谓词的代码 30%效率低于执行index_subqueryLEFT JOIN优化使用Not exists方法的代码。

         

    这就是为什么在 MySQL 中搜索缺失值的最佳方法是使用LEFT JOIN / IS NULLNOT IN而不是NOT EXISTS