dpiuqwwyu187975836 2014-07-04 05:19
浏览 52
已采纳

来自Group_Concat的SQL单独表键

I'm trying to separate the IDPosts column as a single row for each ID (attempting to create a favorite post list). The column next to it has all of the proper columns listed but are grouped, I want to obtain a row for each one grouped together in the favuserposts column. See my picture and query below. Please let me know if you need more information.

enter image description here

Displays everything but cannot display multiple favorite post IDs:

SELECT Users.IDUser, 
       Users.username, 
       Users.profile_picture, 
       Favorites.IDPosts,
       GROUP_CONCAT(DISTINCT coalesce(Favorites.IDPosts,'')) as "favuserposts", 
       ( Select body 
         from Posts 
         where Favorites.IDPosts=Posts.IDPosts 
          AND Users.IDUser=Favorites.IDUser)    
FROM Users
    LEFT OUTER JOIN Favorites ON Favorites.IDUser = Users.IDUser
GROUP BY Users.IDUser HAVING COUNT(IDPosts)>0;
  • 写回答

1条回答 默认 最新

  • dsijovl015728613 2014-07-04 08:20
    关注

    You group by IDUser. So all other fields you select are aggregates in some way. Either you specify the aggregate you want (MIN, MAX, GROUP_CONCAT, etc.) or you get a random match. So let's look at what you select:

    • Users.username = a "random" username for the user id, but as there is just one name per userid of course, you get the one user name for the id
    • Users.profile_picture = same as username; you get the one picture for the user
    • Favorites.IDPosts = a random one of the user's post IDs
    • GROUP_CONCAT(DISTINCT coalesce(Favorites.IDPosts,'')) = string of all distinct IDs
    • ( Select body from Posts ...) = a random one of the user's post bodies

    So if you want a string listing all bodies, then use group_concat, just as you do with the post IDs:

    GROUP_CONCAT(DISTINCT
    ( Select body 
      from Posts 
      where Favorites.IDPosts=Posts.IDPosts 
      AND Users.IDUser=Favorites.IDUser
    )) as bodies 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器