使用每个表的最高ID将两个表中的信息合并为一个

时间:2018-12-18 23:19:42

标签: mysql

我有两个桌子。

表A具有一个唯一的keyid列和一个标识个人的uid列。每个uid都有多个行。

表B与表A相同,但表A中没有其他所有列。

我将创建一个表C,其中包含表A和表B的所有信息

我想要的是一个查询,该查询针对每个uid接受来自Tabla A的最高keyid和来自表B的最高keyid,并插入到表C中。

如何编写这样的查询?

编辑:这是两个表以及我想要的示例

TABLE A
keyid | uid | name | likes
-----------------------------
  1     15    John   nothing
  2     15    John   something
  3     32    Jane   or other

TABLE B
keyid | uid | fruit | 
-----------------------------
  1     15    oranges
  2     32    banana
  3     32    apple


TABLE C (resulting query)
uid | name | likes     | fruit
-------------------------------
 15   John   something   oranges
 32   Jane   or other    apple  

2 个答案:

答案 0 :(得分:1)

对于MySQL或其他支持row_number()over()的数据库的替代方法

merge(A, merge(B, C))
CREATE TABLE TableA(
   keyid  INTEGER  NOT NULL PRIMARY KEY
  ,uid    INTEGER  NOT NULL
  ,name   VARCHAR(20)  NOT NULL
  ,likes  VARCHAR(40)  NOT NULL
);
INSERT INTO TableA(keyid,uid,name,likes) 
VALUES 
(1,15,'John','nothing'),
(2,15,'John','something'),
(3,32,'Jane','or other');
CREATE TABLE TableB(
   keyid  VARCHAR(30) NOT NULL PRIMARY KEY
  ,uid    INTEGER  NOT NULL
  ,fruit  VARCHAR(40)  NOT NULL
);
INSERT INTO TableB(keyid,uid,fruit)
VALUES 
(1,15,'oranges'),
(2,32,'banana'),
(3,32,'apple');
uid | name | likes     | fruit  
--: | :--- | :-------- | :------
 15 | John | something | oranges
 32 | Jane | or other  | apple  

db <>提琴here

答案 1 :(得分:0)

您可以使用CREATE TABLE ... SELECT查询,从每个表中选择uid对应于keyid的最大值为uid的表中的值:

CREATE TABLE TableC AS
SELECT a.uid, a.name, a.likes, b.fruit
FROM (SELECT * 
      FROM TableA a
      WHERE a.keyid = (SELECT MAX(keyid) FROM TableA a2 WHERE a2.uid = a.uid)) a
JOIN (SELECT * 
      FROM TableB b
      WHERE b.keyid = (SELECT MAX(keyid) FROM TableB b2 WHERE b2.uid = b.uid)) b ON b.uid = a.uid

输出(用于您的示例数据):

uid     name    likes       fruit
15      John    something   oranges
32      Jane    or other    apple

Demo on dbfiddle

更新

要将自动增量ID列添加到表中,只需在查询的CREATE TABLE部分中将其指定为列即可:

CREATE TABLE TableC (keyid INT UNSIGNED AUTO_INCREMENT PRIMARY KEY) AS
SELECT a.uid, a.name, a.likes, b.fruit
FROM (SELECT * 
      FROM TableA a
      WHERE a.keyid = (SELECT MAX(keyid) FROM TableA a2 WHERE a2.uid = a.uid)) a
JOIN (SELECT * 
      FROM TableB b
      WHERE b.keyid = (SELECT MAX(keyid) FROM TableB b2 WHERE b2.uid = b.uid)) b ON b.uid = a.uid

输出:

keyid   uid     name    likes       fruit
1       15      John    something   oranges
2       32      Jane    or other    apple