【问题标题】:Is it possible to have a DISTICT statement only on one varible?是否可以仅对一个变量使用 DISTINCT 语句?
【发布时间】:2020-08-03 17:03:59
【问题描述】:

我只想要 'yearLevel' 上的 SELECT DISTINCT 语句(因为我不想只在 yearLevel 上出现任何重复)

image of data displayed on screen

例如,我只想要表中的一条 'yearLevel' 12 记录,并且它是具有最低 'totalSeconds' 的记录

code

$sql = "SELECT firstName, lastName, yearLevel, totalSeconds 

FROM studentInformation
  JOIN record
    ON studentInformation.studentId = record.student_Id

    ORDER BY totalSeconds ASC 
    LIMIT  1  "; 

这样可以吗-

$sql = "SELECT firstName, lastName, DISTINCT yearLevel, totalSeconds 

    FROM studentInformation
      JOIN record
        ON studentInformation.studentId = record.student_Id

        ORDER BY totalSeconds ASC 
        LIMIT  1  "; 

【问题讨论】:

  • 请给出明确的要求,你到底想获取什么
  • 您似乎正在寻找具有分组最小值的行。参见例如herehere.

标签: php mysql select phpmyadmin distinct


【解决方案1】:

如果“firstName”和“lastName”在表“studentInformation”中,并且“yearLevel”和“totalSeconds”在表“record”中,则此查询应该可以工作。它使用相关子查询。我没有对此进行测试;如果它不起作用,请告诉我。

    SELECT a.firstName, a.lastName, b.yearLevel, b.totalSeconds
      FROM studentInformation a
INNER JOIN record b ON a.studentId = b.studentId
     WHERE b.totalSeconds = ( SELECT min(totalSeconds)
                                FROM record
                               WHERE yearLevel = b.yearLevel )
  ORDER BY b.totalSeconds ASC

假设只有“totalSeconds”在表“记录”中,这也可以工作。

    SELECT a.firstName, a.lastName, a.yearLevel, b.totalSeconds
      FROM studentInformation a
INNER JOIN record b ON a.studentId = b.studentId
     WHERE b.totalSeconds = ( SELECT MIN(d.totalSeconds)
                                FROM studentInformation c
                          INNER JOIN record d ON c.studentId = d.studentId
                               WHERE c.yearLevel = a.yearLevel )
  ORDER BY b.totalSeconds ASC

【讨论】:

  • "firstName" 、 "lastName" 和 "yearLevel" 在表 "studentInformation" 中。 “记录”表中只有“totalSeconds”。
  • 好的,我更新了查询。但即使这不起作用,您也应该能够自己修复它。请用谷歌搜索“相关子查询”。
猜你喜欢
  • 2013-08-24
  • 1970-01-01
  • 2013-08-01
  • 2018-07-31
  • 2021-06-27
  • 1970-01-01
  • 1970-01-01
  • 2020-08-05
  • 1970-01-01
相关资源
最近更新 更多