【问题标题】:Using SELECT on 2 or more tables在 2 个或更多表上使用 SELECT
【发布时间】:2015-12-08 22:40:30
【问题描述】:

考虑以下数据库:

浏览器表:

id | name        | description                     | stuff different from cars table
-------------------------------------------------------------------------------------
 1 | Chrome      | Some description
 2 | Firefox     | Some other description
 3 | Vivaldi     | Even more description

汽车表:

id | name        | description                      | stuff different from browsers table
-------------------------------------------------------------------------------------
 1 | Hyundai     | Some korean description
 2 | Ford        | Some ford ther description
 3 | Ferrari     | Even ferrari more description

我需要在 PHP 中获得的输出是 6 个带有 id、名称和描述的对象。我可以用join 关键字来做到这一点吗?如果是这样...如何,我已经悄悄地研究了几个小时。或者也许是不同的方法?

如果我要制作一张我需要获取的输出数据的表格,那就是:

id | name        | description                   
------------------------------------------------
 1 | Hyundai     | Some korean description
 2 | Ford        | Some ford ther description
 3 | Ferrari     | Even ferrari more description
 1 | Chrome      | Some description
 2 | Firefox     | Some other description
 3 | Vivaldi     | Even more description

【问题讨论】:

    标签: php mysql sql select join


    【解决方案1】:

    这不是join 的用例。由于您希望两个表中的行一个接一个,而不是并排,您应该使用union all

    SELECT id, name, description
    FROM   browsers
    UNION ALL
    SELECT id, name, description
    FROM   cars
    

    【讨论】:

    • 这可以用作 SELECT * FROM browsers UNION ALL SELECT * FROM cars 吗?考虑不同的表列?
    • @MerdescuR。如果它们具有相同类型的相同数量的列,以相同的顺序(不管它们的名称) - 是的。如果不是,则不能 - 两个查询必须具有相同数量和类型的列。
    • @MerdescuR。不同的列名应该不起作用 UNION ALL
    猜你喜欢
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多