将两个不同的表组合在一起进行查询
Combing two different tables together for a query
我有两个 table 共享一些列名称,但我并不关心这些。
我只想合并两个 table 并按 created_at 日期排序。对于其中一列,当它来自 table b
时,我想填充一个默认值
我会拿一个这样的table
id
created
title
category
13
2021-01-01
"Hello"
Welcome message
16
2021-01-03
"Hi"
Welcome message
将它与这样的 table 结合起来
id
created
link
13
2021-01-02
so.ca
我正在寻找这样的东西
id
created
link
title
category
0
2021-01-01
null
"Hello"
Welcome message
1
2021-01-02
so.ca
null
tableB item
2
2021-01-03
null
"Hi"
Welcome message
我该如何最好地解决这个问题?我只需要这个 table 来进行查询。我正在使用 rails 和 mysql 5.7。谢谢!
您可以使用:
select (@rn := @rn + 1), created, link, title, category
from ((select ids, created, null as link, title, category
from table1
) union all
(select id, created, link, null, 'tableB item'
from table2
)
order by created
) tt cross join
(select @rn := 0) params
我有两个 table 共享一些列名称,但我并不关心这些。
我只想合并两个 table 并按 created_at 日期排序。对于其中一列,当它来自 table b
时,我想填充一个默认值我会拿一个这样的table
id | created | title | category |
---|---|---|---|
13 | 2021-01-01 | "Hello" | Welcome message |
16 | 2021-01-03 | "Hi" | Welcome message |
将它与这样的 table 结合起来
id | created | link |
---|---|---|
13 | 2021-01-02 | so.ca |
我正在寻找这样的东西
id | created | link | title | category |
---|---|---|---|---|
0 | 2021-01-01 | null | "Hello" | Welcome message |
1 | 2021-01-02 | so.ca | null | tableB item |
2 | 2021-01-03 | null | "Hi" | Welcome message |
我该如何最好地解决这个问题?我只需要这个 table 来进行查询。我正在使用 rails 和 mysql 5.7。谢谢!
您可以使用:
select (@rn := @rn + 1), created, link, title, category
from ((select ids, created, null as link, title, category
from table1
) union all
(select id, created, link, null, 'tableB item'
from table2
)
order by created
) tt cross join
(select @rn := 0) params