2016-08-10 20 views
1

我有一個查詢如下如何寫聯合表中單列的條件?

SELECT s.* 
    , u.email 
    , u.first_name 
    , COUNT(l.tweet_id) as likes 
    , l.user_tweetid 
    FROM social_tweets AS s 
    JOIN users AS u 
    ON s.user_id = u.id 
    left 
    JOIN social_likes AS l 
    ON s.id = l.tweet_id 
WHERE s.user_id IN ($string) 
group 
    by s.id 
ORDER 
    BY created_date DESC 
LIMIT 7 

在這裏,我得到的所有ID。不過,我只是想l.user_tweetid = '246'。我如何才能將WHERE條件應用於該列?如下

回答

2

寫:

SELECT s.*, u.email, u.first_name, COUNT(l.tweet_id) as likes, l.user_tweetid 
FROM social_tweets AS s 
JOIN users AS u ON s.user_id = u.id 
LEFT JOIN social_likes AS l ON s.id = l.tweet_id AND l.user_tweetid = @YourTwiteId 
WHERE s.user_id IN ($string) 
GROUP BY s.id 
ORDER BY created_date DESC 
LIMIT 7; 
0

如果我正確理解你的問題,你的問題,你只需要與特定l.user_tweetid只是一個記錄,你應該在WHERE子句中使用的過濾條件,而不是JOIN子句,即

SELECT s.*, u.email, u.first_name,COUNT(l.tweet_id) as likes,l.user_tweetid 
FROM social_tweets AS s 
     JOIN users AS u ON s.user_id = u.id 
    left JOIN social_likes AS l ON s.id=l.tweet_id 
WHERE s.user_id IN ($string) 
    and l.user_tweetid = '246' 
GROUP BY s.id 
ORDER BY created_date DESC LIMIT 7; 

您可以在SQL join: where clause vs. on clause

找到兩者的區別