我是SQL开发新手。所以我想从SO获得一些帮助。SQL查询获取数据
我有三个表:学生,student_addresses,student_phones。
其架构大致如下:
student
-------
student_id (Primary Key)
student_name
father_name
mother_name
student_addresses
-----------------
student_address_id (Primary Key)
student_id (Foreign Key)
address
zip_code
student_phones
--------------
student_phone_id (Primary Key)
student_id (Foreign Key)
phone_type
phone_number
两个student_addresses和student_phones是的has_many关系。所以我想从学生选择所有字段特定student_id数据但仅从student_addresses匹配的次数(总)和student_phones为student_id数据。我如何获得?
我已经试过此查询,但它返回一个错误:
SELECT students.student_id,student_name,father_name,mother_name,
COUNT(student_addresses.student_id) AS total_addresses,
COUNT(student_phones.student_id) AS total_phones
FROM students,student_phones,student_addresses
WHERE students.student_id = student_phones.student_id AND
students.student_id = student_addresses.student_id AND
students.student_id = 7;
PS:目前我使用这个在PostgreSQL上。不过,我也想在MySQL上工作。那么这是否意味着我需要有两个不同的查询? AFAIK,为此目的,只有一个查询可以同时工作(因为MySQL和PostgreSQL遵循相同的SQL实现,就这个查询要求而言)。
我想知道,如果我可以做到这一点,而不使用GROUP BY。因为,假设学生表有更多的字段,比如说12,那么我将不得不将所有的字段名称都放到SELECT中,以及放在GROUP BY(AFAIK)中,这似乎有点不雅观。
做student_addresses和student_phones有他们自己的主键?如果是这样,他们是什么?另外,你使用PostgreSQL或MySQL? –
@MarkBannister,我没有注意到它有2个不同的数据库。我真的认为它是MySQL。很高兴你指出这一点。 –
@Mark:我编辑了这个问题。谢谢。 –