2013-10-23 31 views
1

我的表:3級的表的SELECT和 「IN」

feeds_time:

user_id | time 
1  | 123123 
2  | 1231111 
3  | 1233223 
... 

users_follow

user_id | follow_id 
1  | 2 
1  | 3 
2  | 3 

而且表的職位 - 但這不是在這個問題很重要。

其實我的查詢如下:

SELECT `id`, `name`, `user_id`, `time`, 'posts' as `what` 
FROM `posts` 
WHERE `user_id` IN (SELECT `follow_id` 
        FROM users_follow WHERE user_id = posts.user_id) 

現在,我想添加一個WHERE:WHERE posts.time > feeds_time.time通過 「電流」 user_id

我該怎麼做?

回答

1

你可以試試這個

使用加入

SELECT A.`id`, A.`name`, A.`user_id`, A.`time`, A.'posts' as `what` 
FROM `posts` A 
JOIN feeds_time B ON A.user_id = B.user_id 
WHERE A.`user_id` IN (SELECT `follow_id` 
        FROM users_follow WHERE user_id = posts.user_id) 
AND A.time > B.time 
1

試試這個:

SELECT * FROM (SELECT `id`, `name`, `user_id`, `time`, 'posts' as `what` 
    FROM `posts` 
    WHERE `user_id` IN (SELECT `follow_id` FROM users_follow 
    WHERE user_id = posts.user_id)) a, feeds_time 
    where a.`time` > feeds_time.time and a.`user_id` = feeds_time.`user_id` 
+0

是否有你的理由使用內部'SELECT'語句而不是'JOIN'來指向'fe eds_time'表? – Saggio

+0

沒有具體的原因,它只是我不擅長連接:( – AsG

0

你可以試試這個查詢:

SELECT a.* 
FROM feeds_time a 
INNER JOIN users_follow b 
    ON a.user_id = b.user_id 
INNER JOIN feeds_time c 
    ON b.user_id = c.user_id 
    AND a.time > b.time