如何写联合表中单列的条件?

时间:2016-08-10 06:24:29

标签: mysql

我的查询如下

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 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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

找到两者的区别