我有三个表。我们称他们为a,b和a_to_b。 a_to_b包含(除其他之外)来自a和b的唯一ID以提供a和b之间的联系(显然)。一个看起来是这样的:帮助一条SQL语句
a_id, max_b, ...
a_to_b看起来像:
a_id, b_id, ...
我想创建一个查询,是这样的:
select a.a_name, a.max_b, a_to_b.(number of times a_id appears in a_to_b) for a, a_to_b where ...
只是我不知道正确的问题,要求谷歌找出如何做到这一点。总之,我不关心a_to_b中b_id的个别出现次数,a_id在该表中出现的次数。
我希望能够看到我想要完成的事情。谢谢您的帮助。
编辑
现在我运行它,我意识到,我很想念查询的一部分。
这是完整的故事。对不起,以前的误导。
表A中:
group_id
other_stuff
表B:
user_id
other_stuff
表A_to_B:
group_id
user_id
m_type (int used to determine user's role in the group)
希望的输出:
a.group_id, a_to_b.count(of group_id where m_type=4), b.user_id (user_id from a_to_b from the group_id that was grouped where m_type=2)
再次,我为转发道歉。第一次问我时应该更加小心。我希望我对这些东西足够熟悉,能够翻译Rasika给出的东西,但我尝试了一堆东西,而且mysql一直对我大吼一声。
更多修改
我没有什么Rasika写道,并与这个烂摊子想出了更多的一些尝试:
select classes.class_id, classes.spaces - ifnull(dUtC.students,0) as openings, classes.semester_id, dUtC.teacher, users.fname, users.lname from (select teachUtC.class_id as class_id, numUtC.students as students, teachUtC.user_id as teacher from (select class_id, count(*) as students from users_to_classes where participation_level=4 group by class_id) as numUtC right join (select class_id, user_id from users_to_classes where participation_level=2) as teachUtC on teachUtC.class_id=numUtC.class_id) as dUtC, classes, users where users.user_id=dUtC.teacher and dUtC.class_id=classes.class_id
它的工作原理,但我不禁想,我这样做错了......我想知道是否有更清晰的方法来编写它。
感谢
你可以尝试将问题提炼到一个更简单的语句。首先,输出表应该是什么样子?什么是最简单的模式,你可以代表你的问题英寸如果你要删除学生等,那么完全这样做。 – jimmyb 2011-04-04 23:31:58
我不确定我是否理解你想提出的建议。我以为我已经尽可能简单地布置了它,但就像我说的,我不知道用文字描述情况的正确词语 – baiano 2011-04-04 23:37:28