简体   繁体   中英

my sql output the same data more than one time when i use select statement

I created three tables "student" and "course" and "lecturer" and I inserted data into them. Now I want to retrieve some data by select.

这些是桌子

When I want to show: Subject taken by Kumar

SELECT STUDENT.NAME, COURSE.SUBJECT1, COURSE.SUBJECT2, COURSE.SUBJECT3
FROM  STUDENT,COURSE
WHERE  STUDENT.COURSE = COURSE.COURSE  = 'MLVK'

it repeats the data more than one time.

I hope anyone help me

All the best

Learn to use proper, explicit, standard JOIN syntax.

And, table aliases:

SELECT s.NAME, c.SUBJECT1, c.SUBJECT2, c.SUBJECT3
FROM STUDENT s JOIN
     COURSE c
     ON s.COURSE = c.COURSE
WHERE c.COURSE  = 'MLVK'

If I were going to use these tables to pick subjects taken by Kumar, I would write something like:

SELECT
s.name, c.course, c.subject1, c.subject2, c.subject3
FROM
student as s 
LEFT JOIN course as c on c.course = s.course
WHERE
s.no_matrik = '23456'
GROUP BY
s.name, c.course, c.subject1, c.subject2, c.subject3

I think this version makes the intent slightly more clear (pick subject for a particular student, Kumar) than the previous answer (select subjects for any student having course = 'MLVK'). This answer will also return information for Kumar even if he has no course value in the Student table (pre-enrollment?).

First of all I would suggest that to model your data properly in BCNF form, where you should have modelled another table to persist subjects and map the lecturer who take that subject.

Ex: (Subject Table)

SubjectId      LECT_ID
----------     ------------
TT234          L123
TT235          L003

and, your Course table would be more of course to subject mapping, like:

CourseName     SubjectId
-------------  --------------
DTM            TT235
DTM            TT695
...

then you use query as:

Select sub.SubjectId, l.NAME
From
  Student s JOIN
  Course c
  on c.CourseName = s.COURSE
  JOIN Subject sub
  on sub.SubjectId = c.SubjectId
  JOIN Lecturer l
  on l.LECT_ID = sub.Lecturer
Where s.NAME = 'Aminah'

the above query will result as:

SubjectId    NAME
---------    ----------
PP563        Ahmad
SS003        Ahmad
PP999        John         

as Ahmad happens to be teaching 2 subjects in course DPG. but if you wish to report distinct Lecturers for Aminah, you can change query as:

SELECT NAME FROM Lecturer where LECT_ID 
in (
Select l.LET_ID
From
  Student s JOIN
  Course c
  on c.CourseName = s.COURSE
  JOIN Subject sub
  on sub.SubjectId = c.SubjectId
  JOIN Lecturer l
  on l.LECT_ID = sub.LECT_ID
Where s.NAME = 'Aminah'
) a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM