MySQL查询多个连接具有不正确的结果

时间:2010-09-16 22:12:57

标签: php sql mysql join

我有3个表格如下:

活动表:

  

activity_id,user_id,type,date

评论表:

  

review_id,activity_id,fishery_id,review,date

更新表格

  

update_id,activity_id,update,date

我想调用活动表链接到用户的所有评论和更新,但是这个查询返回的结果不正确,有什么想法吗?

query('
  SELECT *
  FROM activity as activity    
  LEFT JOIN reviews AS reviews
    ON activity.activity_id = reviews.activity_id    
  LEFT JOIN updates AS updates
    ON activity.activity_id = updates.activity_id    
  WHERE user_id = 1
');

谢谢,马特

3 个答案:

答案 0 :(得分:2)

你试图选择两组不同的数据,我在一个SQL语句中执行此操作的唯一方法是使用union,并创建一些额外的列来区分它们。

SELECT 'review' as type,r.review_id as id,r.fishery_id as fid,
    r.review as review,null as update,r.date as date
FROM reviews r,activity a
WHERE r.activity_id=a.activity_id AND a.user_id=@user_id

UNION

SELECT 'updates' as type,u.update_id as id,null as fid,
    null as review,u.update update,u.date as date
FROM updates u,activity a
WHERE u.activity_id=a.activity_id AND a.user_id=@user_id

答案 1 :(得分:1)

您可能不希望在同一行中进行评论和更新,这似乎是您尝试做的事情。因此,您需要两个查询,而不是一个查询:

SELECT r.review_id, r.fishery_id, r.review, r.date
FROM   reviews r
WHERE  EXISTS (SELECT 1 FROM activity a
               WHERE  a.user_id = @user_id
               AND    a.activity_id = r.activity_id)

SELECT u.update_id, u.update, u.date
FROM   update u
WHERE  EXISTS (SELECT 1 FROM activity a
               WHERE  a.user_id = @user_id
               AND    a.activity_id = u.activity_id)

答案 2 :(得分:0)

仅供参考工作查询:

  SELECT type, review_id, activity.activity_id, review, activity.date, fishery_id
  FROM activity as activity
  JOIN reviews AS reviews
    ON activity.activity_id = reviews.activity_id

  UNION

  SELECT type, activity_id, activity.activity_id, activity, activity.date, NULL
  FROM activity as activity
  JOIN activity AS activity
    ON activity.activity_id = activity.activity_id

  WHERE activity.user_id = 1

  ORDER BY date DESC