SQL内部联接从两个表中输出错误

时间:2018-11-23 20:51:28

标签: mysql sql

学生表:

ID | Family_ID | Student_name | F_name

家庭表:

ID | F_name | Contact_No

我想从重复了family_id的学生那里获得所有记录。(基本上,我想知道学生表中是否有学生的兄弟/姐妹记录。

我这样尝试过,但是输出错误;

SELECT students.*
FROM students
INNER JOIN families 
    ON families.id = students.family_id
    ORDER BY families.id ASC

my query result in image: as you can see some ids are showing once others are more then once, but i think all should appear more then once.

2 个答案:

答案 0 :(得分:3)

如果您只想查看相关人员,则无需将其链接到家庭表。您可以将学生与family_id分组。这是您的查询:

SELECT * 
FROM Student
WHERE family_id IN (SELECT family_id 
                    FROM students 
                    GROUP BY family_id 
                    HAVING COUNT(1)>1)
ORDER BY family_id

答案 1 :(得分:2)

您可以尝试对有不止一个学生行的family_id使用子查询上的联接

SELECT students.*
FROM students
inner join  (
    select students.family_id
    FROM students
    group by students.family_id
    having count(*)>1
) t on t. family_id = students.family_id