合并具有相同数据结构的两个表,然后连接到另一个表

时间:2018-03-16 00:16:51

标签: mysql join union

具有相同数据结构的两个表:

    issues:                        old_issues:
    |id|itemno|issuedate |         |id|itemno|issuedate |
    |1 |200   |2018-02-01|         |1 |200   |2017-12-21|
    |2 |300   |2018-02-03|         |2 |200   |2017-12-20|
    |3 |200   |2018-02-02|         |3 |400   |2016-05-09|
                                   |4 |500   |2016-07-10|

我想将这两个表合并到一个new_issues表中,然后我想将它连接到另一个看起来像这样的表:

items:
|itemnumber|location|ccode|
|200       |DEP     |ARACD|
|300       |DEP     |ARACD|
|400       |SYD     |ARACD|
|500       |DEP     |DVD  |

但我只想用这样的查询选择items

SELECT * FROM items WHERE location = 'DEP' AND ccode = 'ARACD'

然后选择符合此条件的new_issues

SELECT * FROM new_issues WHERE issuedate < '2018-01-01'

这是我尝试过的,但它似乎永远挂在那里,因为问题表中有数百万行:

SELECT i.itemno, new_issues.issuedate
FROM (SELECT * FROM issues UNION SELECT * FROM old_issues) AS new_issues
RIGHT JOIN items i ON i.itemno = new_issues.itemno
WHERE i.ccode = 'ARACD' AND i.location = 'DEP' AND new_issues.issuedate < '2018-01-01'

1 个答案:

答案 0 :(得分:0)

不确定这是否是您正在寻找的但是您尝试了UNION SELECT

SELECT * FROM newitems WHERE location = 'DEP' AND ccode = 'ARACD'
UNION SELECT * FROM olditems WHERE location = 'DEP' AND ccode = 'ARACD' GROUP BY itemno