Mysql 复杂的sql查询:正确连接四个不同的表
我有4个表:users、userpreference、userinfo、useredu 最后三个表使用“id”作为引用表“users”的外键: 待制定的查询: 我需要找到“所有去MSU的单身女性中的顶级音乐” 注意到密歇根州立大学也可以是“明尼苏达州立大学” 到目前为止,我有这个查询,但它没有产生正确的结果Mysql 复杂的sql查询:正确连接四个不同的表,mysql,select,join,Mysql,Select,Join,我有4个表:users、userpreference、userinfo、useredu 最后三个表使用“id”作为引用表“users”的外键: 待制定的查询: 我需要找到“所有去MSU的单身女性中的顶级音乐” 注意到密歇根州立大学也可以是“明尼苏达州立大学” 到目前为止,我有这个查询,但它没有产生正确的结果 select userpreference.preferencevalue as 'Music', COUNT(*) as 'SingleFemaleCount'from users, us
select userpreference.preferencevalue as 'Music', COUNT(*) as 'SingleFemaleCount'from users, userpreference, userinformation
where users.Id = userinformation.Id
and users.Id = userpreference.Id
and userpreference.Id = userinformation.Id
and users.Gender = 'female'
and userinformation.informationvalue = 'single'
and usereducation.school like 'msu%' OR like 'minnesota state%'
and userpreference.preferencetype = 'music' GROUP BY preferencevalue ORDER BY COUNT(distinct users.Id) DESC limit 10
这可能很简单,因为在where子句中需要一些括号:
(usereducation.school如“msu%”或“明尼苏达州%”)
否则,OR的优先级将低于相邻AND
编辑:2011-03-06
下面,我对代码进行了格式化,使其更易于阅读,并将userinformation
和usereducation
签入exists()
子句。我这样做的原因是,如果用户有多个符合您的条件的userinformation
或usereducationat
行,则会影响count()
聚合
select
userpreference.preferencevalue as 'Music',
COUNT(*) as 'SingleFemaleCount'
from users, userpreference
where users.Gender = 'female'
and userpreference.Id = users.Id
and userpreference.preferencetype = 'music'
and exists
(select *
from userinformation
where userinformation.Id = users.Id
and userinformation.informationvalue = 'single')
and exists
(select *
from usereducation
where usereducation.Id = users.Id
and (usereducation.school like 'msu%' OR like 'minnesota state%'))
GROUP BY userpreference.preferencevalue
ORDER BY COUNT(*) DESC limit 10
另一件需要检查的事情是(usereducation.school,如'msu%'或'minnesota state%')
确实找到了所有msu记录。如果结果集不是太大,将运行选择与usereducation不同的学校
,以检查并确保获得了所有记录
最后,我倾向于使用连接语法,如下所示:
select
userpreference.preferencevalue as 'Music',
COUNT(*) as 'SingleFemaleCount'
from users
inner join userpreference on userpreference.Id = users.Id
where users.Gender = 'female'
and userpreference.preferencetype = 'music'
and exists
(select *
from userinformation
where userinformation.Id = users.Id
and userinformation.informationvalue = 'single')
and exists
(select *
from usereducation
where usereducation.Id = users.Id
and (usereducation.school like 'msu%' OR like 'minnesota state%'))
GROUP BY userpreference.preferencevalue
ORDER BY COUNT(*) DESC limit 10
我意识到我完全改变了您的查询,但这是家庭作业,对吗:)Dana是正确的。您还需要将usereducation添加到from子句中:
from users, userpreference, userinformation, usereducation
并将其加入用户。好的,一旦您在“发件人”中添加了usereducation并将其加入到用户表中(您不需要加入其他表,但如果需要,请尝试一下)。请尝试以下方法 在查询中,如果要在WHERE子句中查找等于一个值或另一个值的列,则需要列出两列:
AND (usereducation.school LIKE 'msu%' OR usereducation.school LIKE 'minnesota state%')
我已经这样做了,我忘了添加这篇文章,但是,你怎么检查“MSU”和“明尼苏达州”呢?你的意思是和(像“MSU%”或“明尼苏达州%”这样的用户教育学校)?出于某种原因,这不起作用