如何使用 WordPress API 在 PHP 土地上获取 MySQL table 的列的最大值

How to get the maximum value of a column of a MySQL table, in PHP land, using the WordPress API

这让我很头疼。在 PHP 土地上,我只需要来自名为 work_carousels 的 table 的最大 id。 运行

SELECT MAX(id) FROM work_carousels

直接从 phpMyAdmin 中的命令行 returns

   MAX(id)
   -------
     12

我只需要 PHP 中的那个数字 12(或目前恰好是的任何数字)! WordPress API for interacting with the database 告诉我应该使用

$wpdb->get_results

获取查询结果对应的PHP对象。我试过了

$resultObj = ($wpdb->get_results('SELECT MAX(id) FROM work_carousels'));
$lastAddedCarouselId = $resultObj->MAX(id);  

这没有用,导致内部服务器错误。我也试过

$lastAddedCarouselId = ($wpdb->get_results('SELECT MAX(id) FROM work_carousels'));

但这没有用。还有其他想法吗?

这应该有效:

SELECT id FROM work_carousels ORDER BY id DESC LIMIT 1;

对我来说,这段代码有效

<?php
$max_id = $wpdb->get_var( 'SELECT MAX(id) FROM ' . $wpdb->prefix . 'work_carousels' );

更多关于 $wpdb->get_var() 的信息 https://developer.wordpress.org/reference/classes/wpdb/get_var/