我想合并两个不同列mysql的表。 例如,
表1:
-------------------------------------------------------------
item_id title slug type views updatedAt createdAt
-------------------------------------------------------------
1 sometitle someslg 1 43454 timestamp timestamp
2 sometitle someslg 1 43566 timestamp timestamp
表2:
-------------------------------------------------------------
id ptitle slug pviews updatedAt createdAt
-------------------------------------------------------------
1 sometitle someslg 3434 timestamp timestamp
2 sometitle someslg 6454 timestamp timestamp
3 sometitle someslg 5454 timestamp timestamp
上表是示例。 我已与 UNION 合并。这是我的查询
SELECT * ((SELECT t1.item_id,t1.title,t1.slug,t1.type,t1.views,t1.updatedAt,t1.createdAt
FROM table1
t1) UNION ALL (SELECT t2.id,t2.ptitle,t2.slug,'',t2.pviews,t2.updatedAt,t2.createdAt)) t3
ORDER BY t3.item_id ASC
这很好用在执行查询后我会得到像
这样的结果-------------------------------------------------------------
item_id title slug type views updatedAt createdAt
-------------------------------------------------------------
1 sometitle someslg 1 43454 timestamp timestamp
1 sometitle someslg 3434 timestamp timestamp
2 sometitle someslg 1 43566 timestamp timestamp
2 sometitle someslg 6454 timestamp timestamp
3 sometitle someslg 5454 timestamp timestamp
但是我想在结果中显示一个虚拟列,显示下表所示的行
--------------------------------------------------------------------------
item_id title slug type views updatedAt createdAt from_tbl
--------------------------------------------------------------------------
1 sometitle someslg 1 43454 timestamp timestamp t1
1 sometitle someslg 3434 timestamp timestamp t2
2 sometitle someslg 1 43566 timestamp timestamp t1
2 sometitle someslg 6454 timestamp timestamp t2
3 sometitle someslg 5454 timestamp timestamp t2
答案 0 :(得分:3)
只需添加以下列:
SELECT t3.*
FROM ((SELECT t1.item_id, t1.title, t1.slug, t1.type, t1.views, t1.updatedAt, t1.createdAt, 't1' as from_tbl
FROM table1 t1
) UNION ALL
(SELECT t2.id, t2.ptitle, t2.slug, '', t2.pviews, t2.updatedAt, t2.createdAt, 't2'
)
) t3
ORDER BY t3.item_id ASC
答案 1 :(得分:0)
试试这种方式
SELECT t3.*
FROM ((SELECT t1.item_id, t1.title, t1.slug, t1.type, t1.views, t1.updatedAt, t1.createdAt, '1' as from_tbl
FROM table1 t1
) UNION ALL
(SELECT t2.id, t2.ptitle, t2.slug, '', t2.pviews, t2.updatedAt, t2.createdAt, '2' FROM table2 t2
)
) t3
ORDER BY t3.item_id ASC
答案 2 :(得分:0)
CREATE TABLE table3 AS( 选择 t1。*,t2。* 从table1作为t1,从table2作为t2 哪里 t1.LinkID1 = t2.LinkID2 ); 插入表3
** LinkID1和LinkID2一起都是索引引用