【问题标题】:Select from multiple tables with results labeled by table从多个表中选择,结果由表标记
【发布时间】:2021-12-03 03:11:30
【问题描述】:

是否有任何方法可以进行 MySQL 多表选择,可以标记/标记列来源的表中的列?

table1
tID   name    desc
---------------------
1    foo     lots of foo
2    bar     lots of bar
3    foobar  none of these

table2
oID   tID    orderNo
------------------------
1    1       19001
2    1       19002
3    3       19004
4    2       19005

SELECT t1.*, t2.* FROM table1 t1,table2 t2 WHERE t1.tID=t2.tID ;

输出将是:

tID    name    desc            oID      orderNo
-----------------------------------------------
1      foo     lots of foo      1       19001
1      foo     lots of foo      1       19002
2      foo     lots of bar      4       19005
3      foo     none of these    3       19004

但我正在寻找类似以下输出的东西:

t1.tID    t1.name    t1.desc            t2.oID      t2.orderNo
---------------------------------------------------------------
1         foo        lots of foo        1           19001
1         foo        lots of foo        1           19002
2         foo        lots of bar        4           19005
3         foo        none of these      3           19004

这个小例子代表了我要解决的一个更大的问题。它将允许一个查询,但也能够在解析数据时告诉我数据来自哪个表。

【问题讨论】:

  • 每列都需要别名
  • 使用有意义的别名简单地加入您的表,并从每个表中选择所需的列并为其设置别名。
  • tbale 2 中没有 Oid,t1 没有名字

标签: mysql join select


【解决方案1】:

您可以为每一列使用别名,我建议编写一个适当的连接。

SELECT t1.tID as `t1.tID`,   
       t1.name as `t1.name`,   
       t1.desc as  `t1.desc`,  
       t2.oID  as `t2.oID`, 
       t2.orderNo  as `t2.orderNo`
FROM table1 t1
INNER JOIN table2 on  t1.tID=t2.tID ;

【讨论】:

猜你喜欢
  • 2020-11-22
  • 1970-01-01
  • 1970-01-01
  • 2012-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-04
相关资源
最近更新 更多