MYSQL从表1中获取表2中不存在的记录

时间:2014-10-11 17:55:37

标签: mysql records skip

我创建了一个php函数来从sql表subscriptions中获取记录,我想在mysql_query中添加一个条件来忽略表subscriptions中存在的表removed_items中的记录,这是我的代码;

function subscriptions_func($user_id, $limit){

    $subs = array();

    $sub_query = mysql_query("
        SELECT `subscriptions`.`fo_id`, `subscriptions`.`for_id`, `picture`.`since`, `picture`.`user_id`, `picture`.`pic_id`
        FROM `subscriptions`
        LEFT JOIN `picture`
        ON `subscriptions`.`fo_id` = `picture`.`user_id`
        WHERE `subscriptions`.`for_id` = $user_id
        AND `picture`.`since` > `subscriptions`.`timmp`
        GROUP BY `subscriptions`.`fo_id`
        ORDER BY MAX(`picture`.`since_id`) DESC
        $limit
        ");
    while ($sub_row = mysql_fetch_assoc($sub_query)) {
        $subs [] = array(
            'fo_id'             => $sub_row['fo_id'],
            'for_id'            => $sub_row['for_id'],
            'user_id'           => $sub_row['user_id'],
            'pic_id'            => $sub_row['pic_id'],
            'since'             => $sub_row['since']
        );
    }
    return $subs ;
}

我的解决方案是创建另一个函数来从表removed_items获取记录并设置一个php条件,我调用subscriptions_func()来跳过/取消设置类似subscriptions_func()中记录的记录,如下所示

$sub = subscriptions_func($user_id);
foreach($sub as $sub){
    $rmv_sub = rmv_items_func($sub[‘pic_id’]);

    If($rmv_sub[‘pic_id’] != $sub[‘pic_id’]){
        echo $sub[‘pic_id’];
    }
}

这个解决方案成功地跳过了表removed_items中的项目,但是这个解决方案在数组中存储了存储在变量$ sub中的空白,它在回显的项目中产生了木板斑点。

是否有条件我可以添加到函数subscriptions_func()以删除所有附加条件和检查?

1 个答案:

答案 0 :(得分:0)

假设idsubscriptions的主键,而subs_idremoved_items中的外键,那么您只需要向WHERE添加一个条件}子句。这样的事情应该有效:

...
AND `subscriptions`.id NOT IN (SELECT `removed_items`.subs_id FROM `removed_items`)
...

与您的问题无关: