[英]Select *, max(date) works in phpMyAdmin but not in my code
OK, my statement executes well in phpMyAdmin, but not how I expect it in my php page. 好的,我的语句在phpMyAdmin中执行得很好,但是在我的php页面中却不是这样。
This is my statement: 这是我的声明:
SELECT `egid`, `group_name` , `limit`, MAX( `date` )
FROM employee_groups
GROUP BY `egid`
ORDER BY `egid` DESC ;
This is may table: 这是五月表:
CREATE TABLE `employee_groups` (
`egid` int(10) unsigned NOT NULL,
`date` date NOT NULL,
`group_name` varchar(50) NOT NULL,
`limit` smallint(5) unsigned NOT NULL,
PRIMARY KEY (`egid`,`date`)
) ENGINE=MyISAM DEFAULT CHARSET=cp1251;
I want to extract the most recent list of groups, eg if a group has been changed I want to have only the last change. 我想提取最近的组列表,例如,如果某个组已更改,我只希望最后一次更改。 And I need it as a list (all groups).
我需要它作为列表(所有组)。
Your query might be broken. 您的查询可能已损坏。 You should not select fields that aren't in the group by unless one of the following two conditions apply:
除非满足以下两个条件之一,否则不应选择不在此分组依据中的字段:
The two fields group_name
and limit
appear to break these rules. 两个字段
group_name
和limit
似乎违反了这些规则。 This means that you will get indeterminate results for these columns. 这意味着您将获得这些列的不确定结果。
If you are trying to select the max per group then you should use a slightly different technique. 如果尝试选择每个组的最大值,则应使用稍微不同的技术。 See Quassnoi 's article MYSQL: Selecting records holding a groupwise maximum for a variety of methods you could use.
请参阅Quassnoi的文章MYSQL:选择可以按组使用的最大值的记录 ,以了解可以使用的各种方法。
Here's one way to do it: 这是一种实现方法:
SELECT di.*
FROM (
SELECT egid, MAX(date) AS date
FROM employee_groups d
GROUP BY egid
) dd
JOIN employee_groups di
ON di.egid = dd.egid AND di.date = dd.date
aggregate functions will work in mysql, different to the sql standard. 聚合函数将在mysql中工作,与sql标准不同。 to access the value of
max(date)
from php, you have to alias it: 要从php访问
max(date)
的值,您必须对其进行别名:
SELECT `egid`, `group_name` , `limit`, MAX( `date` ) as maxdate
FROM …
you can then select it like any other colum from php with 然后您可以像从php中选择任何其他列一样选择它
while($row = mysqli_fetch_row($result)) {
echo htmlspecialchars($row['maxdate']);
}
hope that helps 希望能有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.