【问题标题】:Second query within a query using results of first query使用第一个查询的结果的查询中的第二个查询
【发布时间】:2013-11-01 11:57:56
【问题描述】:

以下 select 语句返回学生列表:

SELECT * FROM students2014 ORDER BY LastName

但是,对于每一行,我需要从另一个表 (notes2014) 返回数据,以允许我显示每个学生的最新笔记。选择语句如下:

SELECT Note FROM notes2014 WHERE NoteStudent='$Student'

$Student 表示students2014 数据库中每个学生的ID。但是,此结果仅在查询初始语句后出现。

所以我的问题是,如何在第一个查询中运行第二个查询?

【问题讨论】:

  • 您可能需要加入。

标签: php mysql sql select


【解决方案1】:

你应该像这样查询数据:

select students2014.*, notes2014.note from students2014, notes2014 where students2014.id = notes2014.NoteStudent

【讨论】:

  • 行得通!谢谢!然而,结果排除了目前没有任何相应笔记的任何学生......即使有些学生目前没有笔记,我也需要显示一个完整的列表。
【解决方案2】:

试试这个::

Select 
Student, 
Note 
from 
students2014 s
INNER JOIN notes2014 n on Student = n.NoteStudent
ORDER BY lastName

【讨论】:

  • 恐怕我完全迷失了这个。我已经尝试过了,但我什么也没得到。 studentId 和 student_ID 是什么意思?表示学生ID的列是Student。
  • @PhilHowell:student2014 中的 studentId 列是什么?
  • 它叫Student :) 这只是一个增量值。
【解决方案3】:

代表 OP 发布:

我已经解决了!谢谢你的帮助。我最后使用了左连接:

SELECT * FROM students2014
    LEFT JOIN notes2014 ON students2014.Student = notes2014.NoteStudent
    WHERE students2014.Consultant='$Consultant'
    ORDER BY students2014.LastName

【讨论】:

    猜你喜欢
    • 2015-03-16
    • 1970-01-01
    • 2018-07-30
    • 2014-12-02
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多