如何避免一个查询的匹配ID与另一个查询

时间:2015-08-08 07:51:53

标签: php mysqli mysqli-multi-query

我的第一个查询获得了Table A的所有相关ID,另一个查询从ids获得了所有必要的Table B

现在我想通过上面两个查询都不匹配的ID进行第三次查询。

示例:

  1. 查询返回:1,5,10,15。
  2. 查询返回:5。
  3. 查询想要通过:1,10,15。
  4. 这是我的工作:

    //1st query:
    foreach((array)$f2_ids as $indx => $value) {
        $g = mysqli_query($dbh,"SELECT id FROM update WHERE 
        `to_id`='".$pg_ids[$indx]."' AND `from_id`='".$f2_ids[$indx]."' GROUP BY id") or die(mysqli_error($dbh));
        while ($rows = mysqli_fetch_assoc($g)) {
        $ids[] = $rows['id'];
        }
    }
    
    //2st query:
    foreach((array)$ids as $id) {
        $p = mysqli_query($dbh,"SELECT post_id FROM view WHERE `post_id`='".$id."' AND `user_id` ='".$session->id."'") or die(mysqli_error($dbh));
        while ($rows = mysqli_fetch_assoc($p)) {
        $Vids[] = $rows['post_id'];
        }
    }
    
    //3st query: I tried which not get proper result.
    foreach((array)$ids as $index => $value) {
        if($ids[$index] !== $Vids[$index]){  // avoid match ids
        //echo $ids[$index];
        $j = mysqli_query($dbh,"SELECT * FROM update WHERE `id`='".$ids[$index]."' ORDER BY created DESC");
        }
    }
    

    更新:

    foreach((array)$ids as $id) {
        $p = mysqli_query($dbh,"SELECT * 
        FROM update 
        WHERE `id` = '$id'
        AND `id` NOT IN (SELECT post_id
                FROM view
                WHERE `post_id`='$id'
                AND `user_id`='$myid')
        ORDER BY created DESC") or die(mysqli_error($dbh));
                $rows = mysqli_fetch_assoc($p);
                $id = $rows['id'];
                echo $id;
    }
    

2 个答案:

答案 0 :(得分:1)

查看subqueries

我认为它应该是这样的:

SELECT * 
FROM update 
WHERE `id` NOT IN (SELECT id 
                  FROM update 
                  WHERE `to_id`=".$pg_ids[$indx]."
                  AND `from_id`=".$f2_ids[$indx]."
                  GROUP BY id )
AND `id` NOT IN (SELECT post_id
                FROM view
                WHERE `post_id`=".$id."
                AND `user_id`=".$session->id.")
ORDER BY created DESC

答案 1 :(得分:0)

我认为你应该使用单独的第三个查询,不要从第一个和第二个查询中获取值..