如何从子查询中选择多个列而不是多个相似的子查询?
我正在尝试按查看/下载对图像列表进行排序。我将统计信息存储在另一个表中,每天在其中保存一行。经过几天的搜索,我已经成功地获得了一个有效的 SQL,但它似乎不是很有效,因为我几乎执行了 3 次相同的查询。这是我的表和 SQL:
CREATE TABLE "images_stats" (
"id" integer NOT NULL PRIMARY KEY,
"image_id" integer NOT NULL REFERENCES "images_image" ("id"),
"date" date NOT NULL,
"view_count" integer unsigned NOT NULL,
"download_count" integer unsigned NOT NULL
)
images_list = Images.objects.raw('''
SELECT *,
(SELECT 1.0*SUM(s.view_count)/SUM(s.download_count)
FROM images_stats AS s
WHERE s.image_id = w.id AND s.date < %s AND s.date >= %s) AS ratio,
(SELECT 1.0*SUM(s.view_count)/SUM(s.download_count)
FROM images_stats AS s
WHERE s.image_id = w.id AND s.date < %s) AS global_ratio,
(SELECT COUNT(*)==0
FROM images_stats AS s
WHERE s.image_id = w.id AND s.date < %s) AS count
FROM images_image as w
WHERE w.category_id = %s
ORDER BY count, ratio, global_ratio
''', [date.today(), date.today()-timedelta(days=1), date.today(), date.today(), category.id])
有人知道我如何优化这个 SQL 吗?我有一些 SQL 知识,但显然还不够。
I'm trying to sort a list of images by views/downloads. I'm storing the statistics in a different table where I save a row for each day. After a few days of searching I have managed to get a working SQL but it doesn't seem very efficient since I'm doing almost the same query 3 times. Here are my tables and SQL:
CREATE TABLE "images_stats" (
"id" integer NOT NULL PRIMARY KEY,
"image_id" integer NOT NULL REFERENCES "images_image" ("id"),
"date" date NOT NULL,
"view_count" integer unsigned NOT NULL,
"download_count" integer unsigned NOT NULL
)
images_list = Images.objects.raw('''
SELECT *,
(SELECT 1.0*SUM(s.view_count)/SUM(s.download_count)
FROM images_stats AS s
WHERE s.image_id = w.id AND s.date < %s AND s.date >= %s) AS ratio,
(SELECT 1.0*SUM(s.view_count)/SUM(s.download_count)
FROM images_stats AS s
WHERE s.image_id = w.id AND s.date < %s) AS global_ratio,
(SELECT COUNT(*)==0
FROM images_stats AS s
WHERE s.image_id = w.id AND s.date < %s) AS count
FROM images_image as w
WHERE w.category_id = %s
ORDER BY count, ratio, global_ratio
''', [date.today(), date.today()-timedelta(days=1), date.today(), date.today(), category.id])
Does anybody know how i can optimize this SQL? I have some SQL knowledge but apparently not enough.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)