简体   繁体   English

从php中的sql资源中选择MAX(val)

[英]selecting MAX(val) from a sql resource in php

I have a sql result that looks like this: 我有一个sql结果,如下所示:

   MAX(val)    |   instance
17410742.00    |     0

I need to loop through it in php but I can't seem to select the Max(val) column. 我需要在php中循环它,但我似乎无法选择Max(val)列。 Usually I would do a something like this: 通常我会做这样的事情:

foreach ($sqlmax as $maxrow){
    $myvar=$maxrow['instance'];
}

Which returns the 'instance' value, but I can't get the syntax to retrieving the Max(val) as 返回“实例”值,但我无法获取检索Max(val)的语法

foreach ($sqlmax as $maxrow){
    $myvar=$maxrow['Max(val)'];
}

doesn't work. 不起作用。 I get the error Notice: Undefined index: 我收到错误提示:未定义的索引:

How do I select the Max(val) result in the same way I can select the 'instance' value? 如何以与选择“实例”值相同的方式选择Max(val)结果? Thanks 谢谢

Assign a column name in your query, so you can access the field easier: 在查询中指定列名,以便您可以更轻松地访问该字段:

SELECT MAX(val) AS max_value ....

Then you can access it with 然后你可以访问它

$myvar=$maxrow['max_value']

Use AS in your SQL Query: 在SQL查询中使用AS

SELECT MAX(val) AS max_val, instance FROM table WHERE instance = 0;

Then you will be able to access the column as $myvar=$maxrow['max_val']; 然后,您将能够以$myvar=$maxrow['max_val'];访问该列$myvar=$maxrow['max_val']; .

The query I wrote here is just an example, since you do not provide yours. 我在这里写的查询只是一个例子,因为你不提供你的。

I will go ahead an assume you use mysql and will provide a link to MySQL docs : 我将继续假设您使用mysql并将提供MySQL文档的链接:

A select_expr can be given an alias using AS alias_name. 可以使用AS alias_name为select_expr指定别名。 The alias is used as the expression's column name and can be used in GROUP BY, ORDER BY, or HAVING clauses. 别名用作表达式的列名,可用于GROUP BY,ORDER BY或HAVING子句。 For example: 例如:

SELECT CONCAT(last_name,', ',first_name) AS full_name FROM mytable ORDER BY full_name;

Simply do it like 简单地说就像

select max(val) as mval

and access it like 并访问它

$maxrow['mval']

Just providing an alternate answer, in case you don't want (or are unable to) use AS . 如果您不想(或不能)使用AS ,只需提供备用答案。

The problem here was that the key of the array is case sensitive, so you have to use $maxrow['MAX(val)'] instead of $maxrow['Max(val)'] . 这里的问题是数组的键是区分大小写的,所以你必须使用$maxrow['MAX(val)']而不是$maxrow['Max(val)']

SELECT MAX(val) AS instance 

Access this 访问这个

foreach ($sqlmax as $maxrow){
    $myvar=$maxrow['instance'];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM