-1

Students Table:

ID | Family_ID | Student_name | F_name

Families Table:

ID | F_name | Contact_No

i want to get all records from students where family_id is repeating.(basically i want to know students Brothers/Sisters records if there is any in student table.

i tried it this way but got wrong output;

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.

iMatti
  • 13
  • 6
  • If they dont exist in the families table and you want them returned you would use a left join. otherwise give more details on wrong data and provide data examples – Brad Nov 23 '18 at 20:53
  • @Brad i want only those rows which exist – iMatti Nov 23 '18 at 20:54
  • If you can show the input and output sample ?Btw inner join means common records for some same ids in both the tables in your case. – Himanshu Nov 23 '18 at 20:54
  • This query will give you all the students records whose family ID is present in the family table even if their family ID is not repeated in any other record. – Islam Hassan Nov 23 '18 at 20:58
  • @HimanshuAhuja image attached please check – iMatti Nov 23 '18 at 21:00
  • @IslamEl-Rougy solution i want only repeated ids result? – iMatti Nov 23 '18 at 21:01
  • here is an example of how you can provide you data sample instead of image http://sqlfiddle.com/#!9/92512f/1 – Alex Nov 23 '18 at 21:05

2 Answers2

3

If you want to see only relevant people you don't need to link it to the families table. You can group the student with family_id. Here is your query :

SELECT * 
FROM Student
WHERE family_id IN (SELECT family_id 
                    FROM students 
                    GROUP BY family_id 
                    HAVING COUNT(1)>1)
ORDER BY family_id
Alex
  • 16,739
  • 1
  • 28
  • 51
Zeki Gumus
  • 1,484
  • 7
  • 14
2

You could try using a join on subquery for the family_id that have more that one rows in students

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
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107