简体   繁体   中英

SQL Query in MANY- MANY RELATIONSHIP exactly one record with matching criteria

I have 3 like with many - many relationship As:

TABLE 1 : select * from student;

| id   | name   |
|    1 | sone   |
|    2 | stwo   |
|    3 | sthree |
|    4 | sfour  |
|    6 | ssix   |


TABLE 2 : select * from course;


|  id  | name |
|  100 | CSE  |
|  101 | ECE  |
|  102 | ITI  |

RELATION_SHIP TABLE : select * from student_course
| id   | stu_id | cou_id |
|    1 |      1 |    101 |
|    2 |      2 |    102 |
|    3 |      2 |    100 |
|    4 |      3 |    100 |
|    5 |      3 |    101 |
|    6 |      1 |    101 |
|    1 |      6 |    101 |

I need to write a query to select a student with exactly one course 'CSE' and he should not have any other courses.

Thanks in advance

Use query:

SELECT 
  sc.`stu_id`,
  COUNT(sc.`cou_id`) AS cnt 
FROM
  student_course sc 
GROUP BY sc.`stu_id` 
HAVING cnt = 1 
  AND GROUP_CONCAT(cou_id) LIKE 
  (SELECT 
    id 
  FROM
    course 
  WHERE NAME = 'CSE')

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