帮助SQL语句

时间:2011-04-04 23:24:00

标签: mysql sql

我有三张桌子。我们称他们为a,b和a_to_b。 a_to_b包含(除其他外)来自a和b的唯一id,以提供a和b之间的链接(显然)。看起来像这样:

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

它有效,但我不禁想到我做错了...我想知道是否有更清晰的方式来写这个。

由于

1 个答案:

答案 0 :(得分:2)

您可以使用带有计数的group by来生成此内容。

select a.a_name, a.max_b, count(*) as num_a_id from a join a_to_b on a.a_id=a_to_b.a_id group by a_id
相关问题