mysql JOIN不工作我认为应该如何

时间:2014-03-13 11:26:21

标签: php mysql sql

有人可以解释为什么以下查询返回每行5个副本?我做错了什么?:

(
SELECT user_id, act_id, act_date, act_score, users.posts_check,  'act' AS 
'type' FROM actsWithScore
JOIN users
WHERE user_id
IN ( 1, 5 )
)
UNION ALL (

SELECT user_voter, act_id, vote_date, vote_score, users.posts_check,  'vote' AS 
TYPE FROM votes
JOIN users
WHERE user_voter
IN ( 1, 5 )
)
LIMIT 0 , 50

我得到以下结果:

user_id act_id  act_date            act_score   posts_check         TYPE
1       1       2014-02-05 05:25:25     NULL    2014-03-13 06:52:51  act
1       1       2014-02-05 05:25:25     NULL    0000-00-00 00:00:00  act
1       1       2014-02-05 05:25:25     NULL    0000-00-00 00:00:00  act
1       1       2014-02-05 05:25:25     NULL    0000-00-00 00:00:00  act
1       1       2014-02-05 05:25:25     NULL    0000-00-00 00:00:00  act
1       2       2014-02-05 05:28:16     1       2014-03-13 06:52:51  act
1       2       2014-02-05 05:28:16     1       0000-00-00 00:00:00  act
1       2       2014-02-05 05:28:16     1       0000-00-00 00:00:00  act
1       2       2014-02-05 05:28:16     1       0000-00-00 00:00:00  act
1       2       2014-02-05 05:28:16     1       0000-00-00 00:00:00  act

05是正确的,但不确定它们为何会重复?

1 个答案:

答案 0 :(得分:3)

你忘了加入桌子。它应该是

(
SELECT user_id, act_id, act_date, act_score, users.posts_check,  'act' AS 
'type' FROM actsWithScore
JOIN users on actsWithScore.user_id=users.user_id
WHERE user_id
IN ( 1, 5 )
)
UNION ALL (

SELECT user_voter, act_id, vote_date, vote_score, users.posts_check,  'vote' AS 
TYPE FROM votes
JOIN users on votes.user_id=users.user_id
WHERE user_voter
IN ( 1, 5 )
)
LIMIT 0 , 50