SELECT JOIN MySQL查询中一列的唯一值

时间:2015-08-09 00:23:54

标签: php mysql sql

我有一个查询,用户可以使用JOIN从两个表中提取数据。但我希望结果中的一列特定于user_id,如果与null不匹配,则返回user_id

SQL:

SELECT 
        posts.id, 
        posts.deviceID, 
        posts.type, 
        posts.title,  
        posts.time, 
        SUM(value) AS votes,
        value AS userVote, <--- THIS NEED TO BE UNIQUE TO WHAT THE USER ID IS.          
        FROM posts 
        LEFT JOIN votes 
        on (posts.id = votes.post_id)
        GROUP BY posts.id

如您所见,value AS userVote有SELECT语句。该函数提供user_id php $_POST['user_id']方法,我知道如何输入这个值。这个问题让我感到困惑。

结果快照:

enter image description here

另外,如果这是重复的问题,请提前抱歉,但我想不出在MySQL查询中调用此方法的内容,如果你能告诉我我很感激。

更新

目前我可以使用CASE WHEN votes.user_id = 'USERID' THEN value END AS userVote正确获取值。感谢一个答案,但是当有两个值时,它不会返回用户值,而是null

更新屏幕截图:

enter image description here

2 个答案:

答案 0 :(得分:2)

您想要条件聚合:

SELECT p.id, p.deviceID, p.type, p.title, p.time, 
       SUM(v.value) AS votes,
       MAX(CASE WHEN p.user_id = u.user_id THEN v.value END) as userVote
FROM posts p LEFT JOIN
     votes v
     on p.id = v.post_id
GROUP BY p.id;

注意:如果用户可以多次投票,则可能需要SUM()GROUP_CONCAT(),具体取决于您要查看的内容。

答案 1 :(得分:1)

SELECT 
posts.id, 
posts.deviceID, 
posts.type, 
posts.title,  
posts.time, 
SUM(value) AS votes,
-- value AS userVote,
case when posts.user_id = votes.user_id then value end as userVote,
case when posts.user_id = votes.user_id then post.user_id else null end AS UserIDVote           
FROM posts 
LEFT JOIN votes 
on (posts.id = votes.post_id)
GROUP BY posts.id

添加了case条件,如果两个表都有user_id列,则该条件有效。对于所有匹配,您将获得user_id,否则将获得null

编辑:如果匹配的用户ID需要特定值,则必须从查询中排除值的聚合。

SELECT 
posts.id, 
posts.deviceID, 
posts.type, 
posts.title,  
posts.time,
case when posts.user_id = votes.user_id then value end as userVote,
case when posts.user_id = votes.user_id then post.user_id else null end AS UserIDVote           
FROM posts 
LEFT JOIN votes 
on posts.id = votes.post_id