首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >按字母顺序排列的MYSQL在组中的最后记录

按字母顺序排列的MYSQL在组中的最后记录
EN

Stack Overflow用户
提问于 2014-10-24 21:23:28
回答 1查看 62关注 0票数 0

我正试图遵循“Retrieving the last record in each group”中的答案,但我有一个问题

我的问题是,当我只想要回音数3的时候,我正在回显Y 78430号(即数1和3)。

我试图选择最后一组数据记录,其中最后一个记录是较低的字母。

这里的数据示例(表为“调度位置”):-

代码语言:javascript
复制
 Count       cif_train_uid       cif_stp_indicator        Other Data

   1          Y78430                   p                    zzzzzzz
   2          Z45012                   p                    fffffff
   3          Y78430                   o                    sssssss

在上述数据中,有2×Y78430。我只想回应其中一个。cif_stp_indicator of o (在字母表中低于p)

这是我的密码:-

代码语言:javascript
复制
 $b="SELECT s1.cif_train_uid,s1.cif_stp_indicator,s1.schedule_start_date
 FROM schedulelocation s1
 LEFT JOIN schedulelocation s2
  ON (s1.cif_train_uid AND s1.cif_stp_indicator < s2.cif_stp_indicator)
 WHERE s2.cif_stp_indicator is Null AND s1.cif_train_uid='Y78430' ";             

 $l=mysqli_query($mysql_link,$b);   

 if ($l) {

 while($berths=mysqli_fetch_array($l,MYSQLI_ASSOC))
 {  

 echo $berths['cif_train_uid']; 
 echo $berths['cif_stp_indicator'];
 echo $berths['schedule_start_date'];
 echo "</b>";
 echo "</b>";


 }    

             }          

任何帮助都非常感谢。谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-24 21:42:17

您需要使用聚合查询来查找要显示的适当行,并将其加入到基本信息中。

您的聚合查询如下:

代码语言:javascript
复制
              SELECT cif_train_uid, 
                     MIN(cif_stp_indicator) as cif_stp_indicator
                FROM schedulelocation
            GROUP BY cif_train_uid

它返回一个对(火车,指示器)的列表,其中指示器是火车的最低(词汇第一)一个。

然后,内部将其加入到查询的其余部分,如下所示。

代码语言:javascript
复制
     SELECT s1.cif_train_uid,s1.cif_stp_indicator,s1.schedule_start_date
       FROM (   SELECT cif_train_uid, MIN(cif_stp_indicator) as cif_stp_indicator
                  FROM schedulelocation
              GROUP BY cif_train_uid
            ) AS m 
 INNER JOIN schedulelocation s1
         ON m.cif_train_uid=s1.cif_train_uid 
        AND m.cif_stp_indicator = s1.cif_stp_indicator 
  LEFT JOIN schedulelocation s2
         ON s1.cif_train_uid 
        AND s1.cif_stp_indicator < s2.cif_stp_indicator)
      WHERE s2.cif_stp_indicator is Null    /* IS THIS CORRECT ?? */
        AND s1.cif_train_uid='Y78430'

,注意,,我不能百分之百肯定你的自我加入操作是怎么回事。我认为您的第一个WHERE子句消除了自联接实际发现的所有行。我还是不明白。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26556504

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档