简体   繁体   English

将 2 个 select 语句转换为 MySql 中的单个语句

[英]Converting 2 select statements into a single statement within MySql

I am using two sub-queries to fetch log_msg and log_state from the same table.我使用两个子查询从同一个表中获取log_msglog_state I want to ask how can I convert these 2 sub queries into a single sub query so that I don't need to make call to the same table twice.我想问一下如何将这 2 个子查询转换为单个子查询,以便我不需要两次调用同一个表。

SELECT t1.objectId, t1.name, 
(SELECT a.logs FROM logTable a WHERE a.logId = t1.logId ORDER BY id DESC LIMIT 1) AS log_msg,
(SELECT a.state FROM logTable a WHERE a.logId = t1.logId ORDER BY id DESC LIMIT 1) AS log_state,
FROM table1 t1 WHERE t1.CreateDate >= '2019-12-01';

You can join and filter on the top log record per group as follows:您可以按如下方式加入和过滤每个组的顶部日志记录:

select t1.objectId, t1.name, l.logs, l.state
from table1 t1
inner join logTable l
    on l.id = (select max(l1.id) from logTable l1 where l1.logId = t1.id)

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

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