从多个不相关的表中获取数据

时间:2015-09-23 14:13:33

标签: mysql sql

考虑这两个表:

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

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

如何通过Product1订购Product2created的所有产品?

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

3 个答案:

答案 0 :(得分:2)

<强> 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

答案 1 :(得分:1)

假设两个表具有相同的结构,您可以尝试这个

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

答案 2 :(得分:-3)

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

select product1.*, product2.* from product1 cross join product2;
请注意,交叉连接会使记录倍增。以下是mysql cross join, but without duplicated pair?

的答案