在 SQL 中有一个查询我被严重卡住了,我已经尝试了所有可能的方法但无法得到解决方案。我有 4 个表,分别命名为:user、item、buys、rates。
CREATE TABLE User (
id integer,
name varchar(30),
Primary Key (id)
)
INSERT INTO User(id, name)
VALUES
('1', 'Lorren'),
('2', 'Smith'),
('3', 'Stephen'),
('4', 'David'),
('5', 'Sophie'),
('6', 'Alex'),
('7', 'Henry'),
('8', 'Jasmine'),
('9', 'Anderson'),
('10', 'Bilal')
CREATE TABLE Item (
id integer,
description varchar(50),
category varchar(30),
price integer,
Primary Key (id)
)
INSERT INTO Item(id, description, category, price)
VALUES
('50', 'Princess Diary', 'Book', '8'),
('51', 'Frozen', 'Book', '4'),
('52', 'Tangled', 'Book', '3'),
('53', 'Oak Table', 'Furniture', '370'),
('54', 'Doble Bed', 'Furniture', '450'),
('55', 'Metal Cupboard', 'Furniture', '700'),
('56', 'Levi 501', 'Clothes', '90'),
('57', 'Corduroy Coat', 'Clothes', '230'),
('58', 'Straight Trousers', 'Clothes', '45'),
('59', 'Black Sequin Top', 'Clothes', '85')
CREATE TABLE Buys (
user integer,
item integer,
price integer,
Primary Key (user, item),
Foreign key (user) REFERENCES User(id),
Foreign Key (item) REFERENCES Item(id)
)
INSERT INTO Buys
VALUES ('1', '52', '3'),
('1', '56', '90'),
('2','56','100'),
('2', '54', '450'),
('5', '53', '400'),
('5', '55', '700'),
('5', '59', '90'),
('6', '57', '230'),
('10', '58', '50'),
('8', '50', '8')
CREATE TABLE Rates (
user integer,
item integer,
rating integer CHECK (0<=rating<=5),
Primary Key (user, item),
Foreign key (user) REFERENCES User(id),
Foreign Key (item) REFERENCES Item(id)
)
INSERT INTO Rates
VALUES
('1', '52', '5'),
('1', '56', '3'),
('2', '54', '5'),
('2', '55', '4'),
('2', '56', '2'),
('5', '53', '5'),
('5', '55', '5'),
('8', '50', '1'),
('8', '55', '3'),
('9', '55', '4')
我必须针对每个用户找到他未购买的所有商品,但仅显示其中具有最高平均评级的那些/多个商品。因此,结果应该只显示他没有购买且平均评分最高的那些元素。评分为 1-5,每个项目可能有不同的评分,因此可以计算每个项目的平均评分,但我无法找出每个用户未购买的平均评分最高的项目。我在MYSQL中工作,我被困在这里6天了,甚至我的 friend 都试过没有人能解决它。有人可以帮忙吗?
考虑到当前表的预期输出应该是这样的:
User Items With Highest Average
Lorren 53
Lorren 54
Smith 52
Smith 53
Stephen 52
Stephen 53
Stephen 54
David 52
David 53
David 54
Sophie 52
Sophie 54
Alex 52
Alex 53
Alex 54
Henry 52
Henry 53
Henry 54
Jasmine 52
Jasmine 53
Jasmine 54
Anderson 52
Anderson 53
Anderson 54
Bilal 52
Bilal 53
Bilal 54
最佳答案
好吧,绝对不是我最漂亮的工作,特别是因为我通常不在 MySQL 中工作(编辑:SQLFiddle 已备份。修复了一个内部组,现在可以工作了):
SELECT topItemsAllUsers.* FROM
(SELECT
u.id AS userId,
u.name,
topItems.itemId
FROM
(SELECT
iwa.id AS itemId
FROM
(SELECT
MAX(AverageRating) AS MaxRating
FROM
(SELECT
i.id,
AVG(COALESCE(r.rating, 0)) AS AverageRating
FROM Item i
LEFT JOIN Rates r ON r.item = i.id
GROUP BY i.id
) AS averages
) AS MaxOuterRating
INNER JOIN
(SELECT
i.id,
AVG(COALESCE(r.rating, 0)) AS AverageRating
FROM Item i
LEFT JOIN Rates r ON r.item = i.id
GROUP BY i.id
) as iwa ON iwa.AverageRating = MaxOuterRating.MaxRating
) as topItems
CROSS JOIN
User u
) as topItemsAllUsers
LEFT JOIN Buys b ON topItemsAllUsers.userId = b.user AND topItemsAllUsers.itemId = b.item
WHERE b.user IS NULL
在 TSQL 中,我至少会为该平均评分表使用 CTE。这比最初看起来要困难得多!
编辑:下面是一些解释。首先要获得的是每个项目的平均评分,对没有评分的项目使用 0(因此 COALESCE() 语句):
(SELECT
i.id,
AVG(COALESCE(r.rating, 0)) AS AverageRating
FROM Item i
LEFT JOIN Rates r ON r.item = i.id
GROUP BY i.id)
这将列出每个项目 ID 一次及其平均评分。我将此命名为 averages,实际上我用它查询了两次(第二次将其命名为 iwa。我不记得“iwa”应该是什么意思了。 ..),一旦获得实际最高评价:
SELECT
MAX(AverageRating) AS MaxRating
FROM averages
并将其命名为 MaxOuterRating,然后在 AverageRating = MaxRating 上INNER JOIN将该结果返回到 iwa , 仅获取具有最高评分的项目:
SELECT
iwa.itemId
FROM
MaxOuterRating
INNER JOIN iwa ON iwa.AverageRating = MaxOuterRating.MaxRating
此结果包含在 topItems 别名中。
现在我们只有评分最高的项目,CROSS JOIN 和 User 可以得到一个表,其中包含每个用户的每个最高项目:
SELECT
...
FROM
topItems
CROSS JOIN
Users
此结果在 topItemsAllUsers 中。
最后,对用户 ID 和商品 ID 执行 LEFT JOIN 和 Buys,然后将结果限制为只有那些没有 Buys 的行> 关联的记录(这通常称为排除连接):
SELECT
topItemsAllUsers.*
FROM
topItemsAllUsers
LEFT JOIN Buys b ON topItemsAllUsers.userId = b.user AND topItemsAllUsers.itemId = b.item
WHERE b.user IS NULL
中提琴。这些操作都不是特别困难,但它们嵌套得很厉害,很难看出如何攻击。我不怀疑这可以大大改进,但这确实返回了预期的结果。
关于mysql - 无法在 MySQL 中找出涉及 4 个表的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28972355/
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.
我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在
我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r
我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e
我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳
我在pry中定义了一个函数:to_s,但我无法调用它。这个方法去哪里了,怎么调用?pry(main)>defto_spry(main)*'hello'pry(main)*endpry(main)>to_s=>"main"我的ruby版本是2.1.2看了一些答案和搜索后,我认为我得到了正确的答案:这个方法用在什么地方?在irb或pry中定义方法时,会转到Object.instance_methods[1]pry(main)>defto_s[1]pry(main)*'hello'[1]pry(main)*end=>:to_s[2]pry(main)>defhello[2]pry(main)
我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr
我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类
当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub