简体   繁体   English

从 2 个表 sql 获取最新的重复记录 ID

[英]get newest duplicated records ids from 2 tables sql

i have two tables:我有两张桌子:

Table 1表格1

id | column_1 | column_2 | parent_id | added_at
-------------------------------------------------
1  | 0        |0          | 1        | Date 1
2  | 0        |0          | 1        | Date 2
3  | 1        |0          | 1        | Date 3
4  | 1        |0          | 1        | Date 4

Table 2表 2

id | column_1 | column_2 | parent_id | added_at
-------------------------------------------------
1  | 0        |0          | 1        | Date 5
2  | 0        |0          | 1        | Date 6
3  | 1        |0          | 1        | Date 7
4  | 1        |0          | 1        | Date 8

The result should be for this particular case:结果应该适用于这种特殊情况:

[[2], [4], [1], [2], [3], [4]]

we should get the newest ids when column_1 and column_2 are duplicated in both tables.当 column_1 和 column_2 在两个表中重复时,我们应该得到最新的 id。

i've been trying with something like this one:我一直在尝试这样的事情:

 SELECT x.id
   FROM (
    SELECT t1.column_1, t1.column_2, t1.parent_id, t1.id
    FROM table_1 t1

    UNION

    SELECT t2.column_1, t2.column_2, t2.parent_id, t2.id
    FROM table_2 t2
   ) x
 GROUP BY x.position_x, x.position_y, x.parent_id

But i'm getting [[1], [3]]但我得到[[1], [3]]

Expected result with ids from both tables:来自两个表的 id 的预期结果:

[[2], [4], [1], [2], [3], [4]]

2, 4 are ids from the first table and 1, 2, 3, 4 are ids from the second table 2, 4是第一个表中的 id, 1, 2, 3, 4是第二个表中的 id

may be this is what you want:可能这就是你想要的:

SELECT MAX(id) as last_id
FROM table_1
GROUP BY column_1, column_2
UNION
SELECT id
FROM table_2

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

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