我有两个表需要合并在一起。合并将采用日期表,将其添加到包含其他信息的表中,并在执行操作时创建新记录。有没有办法使用第一条记录中的信息自动完成新记录。例:
表格1:
Tag location Due Date
1 5
表2:
Date
1/1/17
1/7/17
1/14/17
1/21/17
当我合并时,我希望表1看起来像:
Tag location Due Date
1 5 1/1/17
1/7/17
1/14/17
1/21/17
并使用#和location#autofill标记,以便每条新记录显示1和5。
您可以使用交叉联接:
SELECT * FROM table1 CROSS JOIN table2
这会将每个表的每一行连接到另一个表中的每一行。在您发布的有限示例中,您将获得所有不同的日期,标签/位置将重复。如果有两个标记/位置,您将获得8行,每个日期将出现两次,每个标记/位置对将出现4次等。
另一个例子:
TableA TableB
A 1
B 2
C 3
A cross join B
A1 A2 A3 B1 B2 B3 C1 C2 C3
如果我理解你的意思,这将完成这项工作:
CREATE TABLE Table1 (
Tag INT,
Location INT,
DueDate DATE
);
CREATE TABLE Table2 (
MyDate DATE
);
INSERT INTO Table1 VALUES
(1, 5, NULL);
INSERT INTO Table2 VALUES
('2017-01-01'),
('2017-01-07'),
('2017-01-14'),
('2017-01-21');
INSERT INTO Table1 (Tag, Location, DueDate)
SELECT CASE WHEN RN = 1 THEN Tag END,
CASE WHEN RN = 1 THEN Location END,
MyDate
FROM
(
SELECT T1.Tag,
T1.Location,
T2.MyDate,
ROW_NUMBER () OVER (PARTITION BY Tag ORDER BY Tag) AS RN
FROM Table1 T1 CROSS JOIN Table2 T2
) SQ;
DELETE FROM Table1 WHERE DueDate IS NULL;
SELECT *
FROM Table1;
结果:
+------+----------+---------------------+
| Tag | Location | DueDate |
+------+----------+---------------------+
| 1 | 5 | 01.01.2017 00:00:00 |
| NULL | NULL | 07.01.2017 00:00:00 |
| NULL | NULL | 14.01.2017 00:00:00 |
| NULL | NULL | 21.01.2017 00:00:00 |
+------+----------+---------------------+
如果要填充Tag
和Location
列,请使用:
INSERT INTO Table1 (Tag, Location, DueDate)
SELECT T1.Tag,
T1.Location,
T2.MyDate
FROM Table1 T1 CROSS JOIN Table2 T2;
DELETE FROM Table1 WHERE DueDate IS NULL;
SELECT *
FROM Table1;
请用这个。这在mysql Server和MS SQL SERVER中运行良好
select k.Tag,k.Location,u.Mydate Mydate
from
(
SELECT T1.Tag,
T1.Location,
MIN(T2.MyDate) MyDate
FROM Table1 T1 CROSS JOIN Table2 T2
GROUP BY T1.Tag,
T1.Location
)k
RIGHT JOIN
(
SELECT T1.Tag,
T1.Location,
T2.MyDate
FROM Table1 T1 CROSS JOIN Table2 T2
)u ON k.Tag = u.Tag AND k.Location = u.Location
AND k.MyDate = u.Mydate
/*------------------------
OUTPUT
------------------------*/
Tag Location Mydate
----------- ----------- ----------
1 5 2017-01-01
NULL NULL 2017-01-07
NULL NULL 2017-01-14
NULL NULL 2017-01-21
(4 row(s) affected)