简体   繁体   中英

Selecting between multiple sql tables

I have two tables: one for a list of students, and one table to map the student's with some playground toys.

When I select a playground toy, I want to be able to see a list of students with the following restrictions:

  • A student can only have one type of toy at a time. (A student with basketball(s) can't show up in the list when I select soccer ball).
  • A student with a specific toy can have multiple of different colors (A student with a yellow basketball can also have the blue ball).

I'm looking to write an SQL query or convert the tables into a C# list which selects from the student's table such that it will return entries which follow the restrictions. I am using MVC framework in C#, and will be calling the query in the controller through a method which has already been written functionally.

Students
+------------+--------------+
| StudentId  | name         |
+------------+--------------+
|     1      | Bob          |
|     2      | Samuel       |
|     3      | Tim          |
| ...
+------------+--------------+

PlaygroundMap
+-----+-----------------+--------+------------+
| id  | name            | color  | studentid
+-----+-----------------+--------+------------+
| 1   | basket ball     | yellow | 1
| 2   | basket ball     | blue   | 1
| 3   | tennis ball     | black  | 2
| 4   | tennis ball     | red    | 2
| 5   | soccer ball     | purple | 3
| ...
+-----+-----------------+--------+------------+

I'm still new to SQL, so any help would be greatly appreciated. Thanks!

您将必须在Playgroundmap表中为该数据库级别在PlaygroundMap表中名称和Studentid之间的组合主键

How about using the below, I think it matches all of the requirements.

SELECT Students.name, PlaygroundMap.Name, PlaygroundMap.color
FROM Students 
    JOIN PlaygroundMap
        ON Students.StudentId = PlaygroundMap
WHERE Students.StudentID <> (
SELECT Students.StudentID
FROM Students
    JOIN PlaygroundMap
        ON Students.StudentId = PlaygroundMap
WHERE COUNT(PlaygroundMap.name)
GROUP BY PlaygroundMap.Name)
select * from student
where StudentId NOT IN 
    (select distinct StudentId from PlaygroundMap) 
or StudentId IN
    (select distinct StudentId from PlaygroundMap where PlaygroundMapName = @playground)

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