我正试图按照"检索每组中的最后一条记录"中给出的答案进行操作,但出现问题
我的问题是,当我只想回声计数3 时,我正在回声Y78430的两个(即计数1和3)
我试图选择数据组的最后一条记录,其中最后一条是按字母顺序较低的字母。
我的数据示例(表为"schedulelocation"):-
Count cif_train_uid cif_stp_indicator Other Data
1 Y78430 p zzzzzzz
2 Z45012 p fffffff
3 Y78430 o sssssss
在上述数据中有2 X Y78430。我只想附和其中的一个。cif_stp_indicator为o的,即在字母表中低于"p"
这是我的代码:-
$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>";
}
}
非常感谢您的帮助。感谢
您需要使用聚合查询来找到要显示的适当行,并将其与基本信息联系起来。
您的汇总查询如下:
SELECT cif_train_uid,
MIN(cif_stp_indicator) as cif_stp_indicator
FROM schedulelocation
GROUP BY cif_train_uid
它返回一个成对(列车,指示器)的列表,其中指示器是列车的最低(词汇上第一个)指示器。
然后您INNER将它加入到查询的其余部分中,如下所示。
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'
注意我不能100%确定您的自加入操作发生了什么。我认为您的第一个WHERE
子句消除了自联接实际找到内容的所有行。我不明白。