2014-06-13 42 views
0

我想根据user_id是否存在于另一列中来从一列中选择post_ids的列表。如果结果/行不存在,请选择列?

这个想法很简单,就是获取用户尚未与之交互的post_ids列表。

表就是这样与它的内容内容:

+----+---------+---------+--------+---------------------+------------+------+ 
| id | post_id | user_id | rating | last_update   | num_images | url | 
+----+---------+---------+--------+---------------------+------------+------+ 
| 1 | 2938 |  5 |  1 | 2014-06-12 22:54:31 |  NULL | null | 
| 2 | 2938 |  1 |  1 | 2014-06-12 22:54:54 |  NULL | null | 
| 3 | 2940 |  6 |  1 | 2014-06-12 23:36:25 |  NULL | null | 
| 4 | 2943 |  3 |  0 | 2014-06-12 23:39:29 |  NULL | NULL | 
+----+---------+---------+--------+---------------------+------------+------+ 

我的尝试是这样的:

SELECT Distinct post_id 
FROM `table` 
WHERE user_id !=1 

但我仍然得到的结果仍然给了用户已经连接结果与帖子 - 它只是排除包括用户在内的条目。

如果user_id未与比较列中的任何post_id实例连接,那么如何获得结果?

+0

可能是'WHERE user_id是NULL'或'其中USER_ID = 0'? –

回答

1

您的查询应该是:

select distinct(post_id) 
from tableName 
where post_id not in(select post_id from tableName where user_id=1); 
+0

除了小的语法错误外,这很好。结尾部分应该是(从tableName中选择post_id,其中user_id = 1),但是我解决了这个问题并且工作正常。非常感激。 – Orangeman555

+0

是的,纠正它。如果你的工作人员选择它作为答案,那么这个问题就会从未答复的部分中删除。谢谢。 – Sharmi

0

首先,你需要找出post_id列表中给出user_id,然后忽略那些职位的ID。

试试这个:

select distinct post_id 
from table 
where post_id not in (select post_id from table where user_id=1); 
1

我的建议

SELECT Distinct post_id 
FROM `table` T 
WHERE post_id NOT IN (
    /*select posts NOT to be shown */ 
    SELECT post_id 
    FROM `table` T1 
    /* naming the tables differently allows you to make operations 
     with data of the inner selection -T1- AND the outer one -T- 
    */ 
    WHERE T1.user_id = 1 
)