【问题标题】:Combing two different tables together for a query将两个不同的表组合在一起进行查询
【发布时间】:2021-09-08 10:55:32
【问题描述】:

我有两个表共享一些列名,但我并不关心。

我只想合并这两个表并按 created_at 日期排序。对于其中一列,我想在来自表 b 时填充默认值

我要一张这样的桌子

id created title category
13 2021-01-01 "Hello" Welcome message
16 2021-01-03 "Hi" Welcome message

将它与这样的表格结合起来

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

我该怎么做才最好?我只需要这个表来进行查询。我正在使用rails和mysql 5.7。谢谢!

【问题讨论】:

    标签: mysql sql ruby-on-rails mysql-5.7


    【解决方案1】:

    你可以使用:

    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
    

    【讨论】:

    • 我将 row_number 做为“each_with_index”的事情,并考虑将 select 创建为 view,(以便我可以使用模型在 Ruby 中引用它)。取决于这是一次性合并还是重复的事情
    猜你喜欢
    • 1970-01-01
    • 2012-11-05
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    相关资源
    最近更新 更多