【问题标题】:Fetch data from multiple unrelated tables从多个不相关的表中获取数据
【发布时间】:2015-09-23 22:45:06
【问题描述】:

考虑这两个表:

Product1
----------
id
created

Product2
---------
id
created

如何从Product1Product2 获取由created 订购的所有产品?

注意:Product1Product2 表格只是解释我的案例的例子,它们并不反映现实。请不要为此争论。

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    You can Combining Result Sets by Using MySQL UNION

    SQLFiddle

    SELECT * FROM (select p1.id, p1.created from product1 p1
    UNION ALL
    select p2.id, p2.created from product2 p2) A 
    order by created
    

    (select p1.id, p1.created from product1 p1)
    UNION ALL (select p2.id, p2.created from product2 p2)
    ORDER BY created
    

    【讨论】:

    • 结果应按 OP 所述排序。
    • @ElonThan 使用 Order By 子句修改了答案。
    【解决方案2】:

    假设两个表的结构相同,你可以试试这个

    SELECT
        'Product1' AS FromTable
        ,id
        ,created
    FROM
        Product1
    UNION
    SELECT
        'Product2' AS FromTable
        ,id
        ,created
    FROM
        Product2
    ORDER BY created
    

    【讨论】:

    • 如果表是互斥的,则使用UNION ALL,因为它更快。
    • 结果应按 OP 所述排序。
    • 是的,但我不能使用 orderby
    【解决方案3】:

    使用交叉连接(也称为笛卡尔连接)

    select product1.*, product2.* from product1 cross join product2;
    请注意,交叉连接的作用会使记录倍增。这是mysql cross join, but without duplicated pair?的答案

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      • 2021-07-16
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      相关资源
      最近更新 更多