我是 SQL 开发新手。所以我想从SO那里得到一些帮助。
我有三个表:student、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 中的所有字段,但仅选择 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) 中,这看起来有点不优雅。
最佳答案
这应该适用于 MySQL 和 PostgreSQL:
SELECT s.student_id,
max(s.student_name) student_name,
max(s.father_name) father_name,
max(s.mother_name) mother_name,
COUNT(distinct a.student_address_id) total_addresses,
COUNT(distinct p.student_phone_id) total_phones
FROM students s
LEFT JOIN student_phones p ON s.student_id = p.student_id
LEFT JOIN student_addresses a ON s.student_id = a.student_id
WHERE s.student_id = 7
GROUP BY s.student_id
关于mysql - SQL查询获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17806193/