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 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?