我有 2 個表,即entry和entry_log,其架構如下:
入口:
id 數字主鍵
名稱 VARCHAR2(100)
入口日志:
id 數字主鍵
parent_id NUMBER NOT NULL --> 約束 el FOREIGN KEY (parent_id) REFERENCES entry (id)
user_id NUMBER NOT NULL --> 約束 rl_uk FOREIGN KEY (user_id) REFERENCES user (id)
注意:用戶是我擁有的另一張表。
對于條目表中的每一行,我可以在 entry_log 表中有多行,其中條目日志表實際上包含 parent_id 和對條目表中的一行進行修改的用戶。
基本上,entry 是實際的表,每次在 entry 表中發生創建或更新時,都會在 entry_log 表中插入一行。
我需要一個查詢,以便它回傳以下列: id from entry table name from entry table max(id) from entry_log table where parent_id in entry_log = id in entry table
我有以下有效的查詢,但我想實作這一點而不必使用子查詢來提高性能。
select max(log_id) as log_id from (
SELECT
entry_log.id log_id,
entry_log.parent_id
FROM
entry
INNER JOIN entry_log ON entry_log.parent_id = entry.id
) group by parent_id
)
SELECT
entry.id,
entry.name,
mif.log_id "MAX_ID",
FROM
entry
INNER JOIN entry_log ON entry_log.parent_id = entry.id
INNER JOIN max_id_finder mif ON mif.log_id = entry_log.id
WHERE 1=1
有沒有更好的方法可以在不影響性能的情況下實作這一目標?
uj5u.com熱心網友回復:
請檢查以下解決方案是否適合您:
select a.*, b.* from entry a
inner join (select id, max(p_id) as p_id, `name` from entry_log group by p_id) b
on a.id = b.p_id
使用的資料集:
CREATE TABLE `entry` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
CREATE TABLE `entry_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`p_id` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_p_id` (`p_id`),
CONSTRAINT `fk_p_id` FOREIGN KEY (`p_id`) REFERENCES `entry` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=latin1;
insert into entry values (1, "A1");
insert into entry values (2, "A2");
insert into entry values (3, "A3");
insert into entry values (4, "A4");
insert into entry values (5, "A5");
insert into entry values (6, "A6");
insert into entry values (7, "A7");
insert into entry values (8, "A8");
insert into entry_log values (1, 1, "P001");
insert into entry_log values (2, 2, "P002");
insert into entry_log values (3, 1, "P003");
insert into entry_log values (4, 2, "P004");
insert into entry_log values (5, 3, "P005");
insert into entry_log values (6, 1, "P006");
insert into entry_log values (7, 2, "P007");
insert into entry_log values (8, 5, "P008");
insert into entry_log values (9, 2, "P007");
insert into entry_log values (10, 4, "P008");
insert into entry_log values (11, 7, "P001");
insert into entry_log values (12, 8, "P002");
insert into entry_log values (13, 6, "P003");
insert into entry_log values (14, 6, "P004");
insert into entry_log values (15, 3, "P005");
insert into entry_log values (16, 7, "P006");
insert into entry_log values (17, 2, "P007");
insert into entry_log values (18, 5, "P008");
uj5u.com熱心網友回復:
感謝用戶1300830
以下查詢完美運行。
SELECT
entry.id,
entry.name,
entry_log.log_id,
FROM
entry
INNER JOIN (SELECT max(id) as log_id, parent_id from entry_log group by parent_id) entry_log ON entry_log.parent_id = entry.id
WHERE 1=1
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/485554.html
