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条)

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)