【问题标题】:Selecting between multiple sql tables在多个 sql 表之间进行选择
【发布时间】:2016-01-12 16:40:32
【问题描述】:

我有两张表格:一张是学生名单,一张是学生的地图和一些游乐场玩具。

当我选择一个游乐场玩具时,我希望能够看到一个列表 有以下限制的学生:

  • 学生一次只能拥有一种玩具。 (当我选择足球时,有篮球的学生无法出现在列表中)。
  • 拥有特定玩具的学生可以拥有多种不同的颜色(拥有黄色篮球的学生也可以拥有蓝色球)。

我正在寻找编写 SQL 查询或将表转换为 C# 列表,该列表从学生表中进行选择,以便返回遵循限制的条目。我在 C# 中使用 MVC 框架,并将通过已经在功能上编写的方法在控制器中调用查询。

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
| ...
+-----+-----------------+--------+------------+

我还是 SQL 新手,因此我们将不胜感激任何帮助。谢谢!

【问题讨论】:

  • A SELECT 不会管理数据约束。将数据放入表中时,您需要对其进行管理。
  • “我需要一个 SQL 查询”,所以你希望我们为你做这件事吗?
  • 当它脱离表格进入列表时怎么样?如果我将这两个表提取到一个列表中,我可以使用一些运算符根据他们在 PlaygroundMap 表中的 ID 从列表中删除学生吗?
  • @cFrozenDeath 我期待指导,如果我的措辞听起来有点苛刻,请见谅。
  • @ALam,如果一个学生确实有不止一个玩具,你如何选择展示哪个,哪个违反了限制?

标签: c# mysql sql select multiple-tables


【解决方案1】:

您必须在 playgroundmap 表中为在数据库级别在 playgroundMap 表中的 name 和 studentid 之间创建一个复合主键

【讨论】:

    【解决方案2】:

    使用下面的怎么样,我认为它符合所有要求。

    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)
    

    【讨论】:

    • 感谢您的建议,我会研究一下。
    【解决方案3】:
    select * from student
    where StudentId NOT IN 
        (select distinct StudentId from PlaygroundMap) 
    or StudentId IN
        (select distinct StudentId from PlaygroundMap where PlaygroundMapName = @playground)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 1970-01-01
      • 2012-03-12
      • 2021-02-19
      • 2013-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多