MYSQL-从联接中选择最新的行

MYSQL-从联接中选择最新的行,mysql,Mysql,我正在尝试进行常规联接,但使用where子句从history_items表中选择最新条目 SELECT h.history_id, Date_format(From_unixtime(h.timestamp), '%d %m %Y') AS 'date', h.status, h.product_id, p.serial_number, p.product_name, p.site_name, p.site_postcode, Date_forma

我正在尝试进行常规联接,但使用where子句从history_items表中选择最新条目

SELECT h.history_id,
   Date_format(From_unixtime(h.timestamp), '%d %m %Y') AS 'date',
   h.status,
   h.product_id,
   p.serial_number,
   p.product_name,
   p.site_name,
   p.site_postcode,
   Date_format(From_unixtime(i.timestamp), '%d %m %Y') AS 'last_update',
   i.feedback
FROM   history h
   LEFT JOIN products p
          ON h.product_id = p.product_id
   LEFT JOIN history_items i
          ON h.history_id = i.history_id
WHERE  i.timestamp = (SELECT Max(i.timestamp)
                  FROM   history_items)
GROUP  BY i.history_id
ORDER  BY h.timestamp DESC  

我正在选择Maxi.timestamp-这仍然没有返回历史项目表中的最新条目。

我认为您的问题在于:

WHERE  i.timestamp = (SELECT Max(i.timestamp)
              FROM   history_items)
我不应该在那里,它应该是Maxtimestamp而不是Maxi.timestamp

否则Mysql将真正选择i.timestamp行的值。因此,如果时间戳为1,则其计算结果如下:

WHERE 1 =(SELECT Max(1) FROM hsitory_items)
基本上是

WHERE i.timestamp = i.timestamp

我打赌你现在明白了。这就是返回所有行的原因。

因为您无论如何都在按时间戳排序,并按h.timestamp DESC排序,所以实际上根本不需要下面的WHERE条件。另外,下面代码中的子查询错误地引用了其他答案中已经提到的列

WHERE  i.timestamp = (SELECT Max(i.timestamp)
                  FROM   history_items)

对不起,如果我现在问了一个愚蠢的问题。但是为什么他不需要子查询呢?h、 时间戳与i.timestamp没有任何关系。我做错了什么?@DoktorOSwaldo,因为这是不必要的,因为无论如何都要在i.timestamp=选择Maxi.timestamp。。。然后再次订购。。。好吧,虽然绝对不确定,但有点猜测,如果我不得不猜测我会同意你的话,就不需要了。但这确实很难从这个问题中分辨出来。因为可能有多个历史记录的h共享同一条目i。但是,是的,你很可能是对的。感谢您的解释。请参阅: