选择加入2个表和两个表的最新记录
Posted
技术标签:
【中文标题】选择加入2个表和两个表的最新记录【英文标题】:select join 2 tables and latest records of both tables 【发布时间】:2022-01-16 11:59:02 【问题描述】:我有 2 张桌子,而且很热。我需要为每个 symbol_id 选择加入两个表的最新记录
SELECT
`board`.`id`,
`board`.`symbol_id`,
`board`.`symbol`,
`board`.`t_volume`,
`board`.`unix_timestamp`,
`board`.`time`,
`board`.`date`,
`hot`.`id`,
`hot`.`time`,
`hot`.`date`,
`hot`.`buy_repeat`,
`hot`.`sell_repeat`
FROM `board`
LEFT JOIN `hot`
ON `hot`.`symbol_id` = `board`.`symbol_id`
WHERE `board`.`unix_timestamp` = (
SELECT `board`.`unix_timestamp`
FROM `board`
ORDER BY unix_timestamp DESC
LIMIT 1
)
AND `board`.`symbol_id` = '34557241988629814'
GROUP BY `hot`.`symbol_id`
ORDER BY `hot`.`id` DESC
【问题讨论】:
【参考方案1】:您的问题缺乏详细信息(mysql 版本、表声明、示例数据和预期输出示例),但我认为这就是您要寻找的。p>
这适用于 MySQL
两个子查询使用 LEFT JOIN ... IS NULL 技术来获取每个 symbol_id 的最新(按 id)记录。然后,根据您的尝试,派生表是左联接的。
SELECT
`b_latest`.`id`,
`b_latest`.`symbol_id`,
`b_latest`.`symbol`,
`b_latest`.`t_volume`,
`b_latest`.`unix_timestamp`,
`b_latest`.`time`,
`b_latest`.`date`,
`h_latest`.`id`,
`h_latest`.`time`,
`h_latest`.`date`,
`h_latest`.`buy_repeat`,
`h_latest`.`sell_repeat`
FROM (
SELECT
`b1`.`id`,
`b1`.`symbol_id`,
`b1`.`symbol`,
`b1`.`t_volume`,
`b1`.`unix_timestamp`,
`b1`.`time`,
`b1`.`date`
FROM board b1
LEFT JOIN board b2 ON (b1.symbol_id = b2.symbol_id AND b1.id < b2.id)
WHERE b2.id IS NULL
) AS b_latest
LEFT JOIN (
SELECT
`h1`.`id`,
`h1`.`symbol_id`
`h1`.`time`,
`h1`.`date`,
`h1`.`buy_repeat`,
`h1`.`sell_repeat`
FROM hot h1
LEFT JOIN hot h2 ON (h1.symbol_id = h2.symbol_id AND h1.id < h2.id)
WHERE h2.id IS NULL
) AS h_latest
ON b_latest.symbol_id = h_latest.symbol_id
对于 MySQL 8.0 及更高版本,您可以使用 Window Functions -
WITH `b_latest` AS (
SELECT
`b1`.`id`,
`b1`.`symbol_id`,
`b1`.`symbol`,
`b1`.`t_volume`,
`b1`.`unix_timestamp`,
`b1`.`time`,
`b1`.`date`,
ROW_NUMBER() OVER (PARTITION BY `symbol_id` ORDER BY `id` DESC) AS `rn`
FROM `board` `b1`
), `h_latest` AS (
SELECT
`h1`.`id`,
`h1`.`symbol_id`
`h1`.`time`,
`h1`.`date`,
`h1`.`buy_repeat`,
`h1`.`sell_repeat`,
ROW_NUMBER() OVER (PARTITION BY `symbol_id` ORDER BY `id` DESC) AS `rn`
FROM `hot` `h1`
)
SELECT
`b_latest`.`id`,
`b_latest`.`symbol_id`,
`b_latest`.`symbol`,
`b_latest`.`t_volume`,
`b_latest`.`unix_timestamp`,
`b_latest`.`time`,
`b_latest`.`date`,
`h_latest`.`id`,
`h_latest`.`time`,
`h_latest`.`date`,
`h_latest`.`buy_repeat`,
`h_latest`.`sell_repeat`
FROM `b_latest`
LEFT JOIN `h_latest`
ON `b_latest`.`symbol_id` = `h_latest`.`symbol_id`
AND `h_latest`.`rn` = 1
WHERE `b_latest`.`rn` = 1
【讨论】:
以上是关于选择加入2个表和两个表的最新记录的主要内容,如果未能解决你的问题,请参考以下文章