dongyong5255 2017-09-03 20:00
浏览 195
已采纳

MySQL ORDER BY来自另一个表的“count(*)和2个其他参数”

I have been struggling with this problem for about month.. Have been searching and reading many posts, but still can't figure out, how to make this work..

Basically: I got 2 database tables fun_posts and fun_post_upvotes And I want to

SELECT * 
FROM fun_posts 
ORDER BY (HOTTEST POSTS(MOST UPVOTED THIS WEEK))

This is my latest code, that won't work

SELECT * 
FROM fun_posts 
ORDER BY (SELECT count(*), image_id, date 
          FROM fun_post_upvotes 
          GROUP BY image_id 
          ORDER BY DATE(date) > (NOW() - INTERVAL 7 DAY) DESC, 
                   count(*) DESC, 
                   date DESC)

If I divide this line into 2 different SELECT functions, they work. I can select simple posts and I can select upvotes count ordered like I want.

But If I make them into one line like that, I get following error:

#1241 - Operand should contain 1 column(s)

EDIT NR 1:

fun_posts table Image fun_post_upvotes table Image

Problem with Answer that I checked:

Here, look how posts are ordered in my select function. (It selects like I want) 10->134->132->2->13

Image

And here with given code (It selects image, but not in that order) 10->122->39->8->110

Image

  • 写回答

1条回答 默认 最新

  • donglian4770 2017-09-03 20:07
    关注

    You can use a join to do this

    SELECT fp.*, fpu.`cnt`
    FROM fun_posts fp
    LEFT JOIN ( SELECT image_id, COUNT(*) AS cnt
           FROM fun_post_upvotes
           WHERE `date` > (NOW() - INTERVAL 7 day)
           GROUP BY image_id
         ) fpu ON ( fpu.image_id = fp.id )
    ORDER BY fpu.cnt DESC, fp.`date` DESC, fp.`id` DESC;
    

    It selects a list from fun_post_upvotes grouped by image_id and counts the amount of rows. That list is returned to the main query and matches (LEFT JOIN) on fp.id. The query will first show the item with the most upvotes in the past 7 days, than the least. If no upvotes are found, the result will still return them, but at the bottom in no specific order.

    You can edit the order by, to obtain the items in the order you like.

    Here a sqlfiddle.com

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败