dpf71390 2015-08-09 00:23
浏览 174
已采纳

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

I have an query where user can pull data from two table with JOIN. but I would like one columns in the result to be specific to the user_id or return null if it doesn't match the 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

As you can see there is SELECT statement of value AS userVote. the function provides user_id with php $_POST['user_id'] method, I know how to input this value. the query is confusing to me a little.

Result in snapshot:

enter image description here

Also, sorry in advance if this is duplicated question, but I can't think of what this method is called in MySQL query, if you can tell me I appreciate it.

UPDATE:

Currently I can get the value correctly with CASE WHEN votes.user_id = 'USERID' THEN value END AS userVote Thanks to one answer, but when there are two values it wouldn't return user value but null.

Update Screenshot:

enter image description here

  • 写回答

2条回答 默认 最新

  • doumei1955 2015-08-09 01:47
    关注

    You want conditional aggregation:

    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;
    

    Note: if a user could vote multiple times, you might want SUM() or GROUP_CONCAT(), depending on what you want to see.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)