[英]Select within select for MYSQL
I am trying to SELECT specific lines of data from a MYSQL database 我正在尝试从MYSQL数据库中选择特定的数据行
The database is as follows 数据库如下
Count id Startstation stp
1 A1234 Nottingham o
2 A1234 Nottingham p
3 B2345 Nottingham p
4 C6789 Leeds o
I would like to select all the Nottingham stations but not repeat the same id. 我想选择所有的诺丁汉车站,但不要重复相同的ID。 Also an stp code of o takes priority over an stp of p. 同样,o的stp码比p的stp优先。
So I am looking for an output as follows: 所以我正在寻找如下输出:
A1234 Nottingham o
B2345 Nottingham p
Here is the code I have been trying to use but I cannot get it to work 这是我一直在尝试使用的代码,但我无法使其正常工作
require('connect_db.php');
mysqli_select_db($mysql_link,"timetable");
$q="select * from (SELECT id,startstation, stp, ROW_NUMBER() OVER (PARTITION BY id ORDER BY stp DESC) rnk FROM railtest WHERE startstation="Nottingham") where rnk = 1";
$r=mysqli_query($mysql_link,$q);
if ($r)
{
while ($row=mysqli_fetch_array($r,MYSQLI_ASSOC))
{
echo $row['startstation'] . " " . $row['id']." ".$row['stp'];
echo "<br>";
}
}
else {echo '<p>'.mysqli_error($mysql_link).'</p>' ;}
mysqli_close($mysql_link);
I am getting a Parse error with my select statement 我的选择语句出现解析错误
Hope some one can help 希望有人能帮忙
Thanks 谢谢
SELECT `id`,`startstation`,min(`stp`) as stp
FROM `railtest`
WHERE `startstation`='Nottingham'
GROUP BY `id`, `startstation`
Group on the two columns that are the same and since o
comes before p
you can just select the min
value. 在相同的两列上分组,由于o
在p
之前,因此您只需选择min
。 Obviously this works when there are two values for stp, more and you can put them alphabetically by priority or use a correlated sub-query to get the value for stp. 显然,当stp有两个值(更多)时,此方法有效,您可以按优先级将它们按字母顺序排列,也可以使用相关的子查询来获取stp的值。
SELECT `id`,`startstation`, `stp`
FROM `railtest`
WHERE `startstation`='Nottingham'
GROUP BY `id`
ORDER BY `stp` ASC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.