我的mysql JOIN怎么了,我没有得到正确的结果

时间:2013-11-08 04:59:52

标签: mysql ubuntu

表A有 userIdentity(primaryKey) 用户名 userPhoneNumber

表B有 someOtherKey(的PrimaryKey) 的UserIdentity 用户位置

当我运行

时,我获得了22行具有唯一userIdentity的行
SELECT *
FROM tableB 
WHERE tableB.timeStamp > '2013-11-1' 
GROUP BY tableB.userIdentity ;

我运行时只获得2行(我打算在上面的查询中提取22行的名称和电话号码)

SELECT tableA.userName, tableA.phonePhoneNumber 
FROM tableB
JOIN tableA 
WHERE tableB.timeStamp > '2013-11-1'
GROUP BY tableB.userIdentity
    AND tableA.identityHash = tableB.identityHash;

2 个答案:

答案 0 :(得分:2)

两者之间的公共字段userIdentity应位于ON之后的JOIN子句而不是identityHash,例如:

 SELECT tableA.userName, tableA.phonePhoneNumber 
 FROM tableB
 JOIN tableA
 ON tableB.userIdentity = tableA.userIdentity 
 WHERE tableB.timeStamp > '2013-11-1'
 GROUP BY tableB.userIdentity

检查我的Fiddle Demo

答案 1 :(得分:1)

我很确定你的'AND'条款是错误的。你可能想做的是:

SELECT tableA.userName, tableA.phonePhoneNumber 
FROM tableB JOIN tableA 
WHERE tableB.timeStamp > '2013-11-1'
    AND tableA.identityHash = tableB.identityHash
GROUP BY tableB.userIdentity;