0

好的,所以我有一个名为 posts 的表,我试图删除重复项,条件是如果 post_id 之一等于 post_dat_id 并且只有在 post_data_id == post_id 的 post_type 为 2 时才删除它。

帖子结构

post_id || post_data_id || post_type || post_user_id
==================================
1 || NULL || 0 || 10210

2 || 1 || 2 || 201020 <-- it shouldn't show this one because it meets the condition that post_type == 2 && the post_data_id is equal to one of the post_id. EDIT: also notice how this id = 2 but the post_data_id = 1. It is impossible for a row ot have the same post_id & post_data_id

2 || 1 || 0 || 202020

3 || 6 || 2 || 202020

我的mysql:

 SELECT p.*
 FROM posts p
 LEFT JOIN following f ON f.user_id =1
 AND p.post_user_id = f.follower_id 
 WHERE post_user_id =1
 OR f.user_id IS NOT NULL 
 ORDER BY  `p`.`post_time` DESC 
 LIMIT 0 , 10

编辑:我不想删除代码,如果满足我选择的条件,我想做的就是不显示该结果。另外我已经在使用左连接,因为我的 sql 代码需要检查下表来获取用户 ID

编辑 2:我还将 post_data 更改为 post_data_id 所以它现在是一个纯 int

4

2 回答 2

0

尚未测试此代码,但我会执行以下操作:

select from posts p where p.id not in
(select q.id from posts q
where q.post_data = q.post_id and q.post_type = 2);
于 2013-08-07T18:47:15.740 回答
0

我不确定我是否完全理解了您的问题,但听起来您需要使用 LEFT JOIN 来删除符合给定条件的行 -

SELECT p1.*
FROM posts p1
LEFT JOIN posts p2
    ON p1.post_data_id = p2.post_id
    AND p1.post_type = 2
LEFT JOIN following f
    ON f.follower_id = 1
    AND p1.post_user_id = f.user_id 
WHERE p2.post_id IS NULL
AND (p1.post_user_id = 1 OR f.user_id IS NOT NULL)
ORDER BY  p1.post_time DESC 
LIMIT 0, 10

随着数据集的增长,这将对性能产生相当大的影响,并且看起来您的数据结构存在一些问题。您可能想查看将自引用外键移动到其自己的字段。

于 2013-08-07T19:12:24.800 回答