【问题标题】:There are two columns in the new table(table1 join table2) which have the same column name, how to get the values of both respectively新表(table1 join table2)中有两列具有相同的列名,如何分别获取两者的值
【发布时间】:2009-12-23 04:32:12
【问题描述】:
select * from table1 join table2 on table1.column3=table2.column4 where ...
...
$row=mysql_fetch_assoc($result);

但是,新表(table1 join table2)中有两列具有相同的列名,如何分别获取两者的值?

【问题讨论】:

    标签: php sql mysql


    【解决方案1】:

    使用别名来专门调用列

    SELECT table_1.id as table_1_id, table_2.id as table_2_id

    您必须以这种方式列出至少一个表中的所有或大部分列,但您可以访问多个表中具有相同名称的列。

    【讨论】:

    • 谢谢您,先生@prodigitalson 您让我过得愉快,先生。再次感谢。
    【解决方案2】:

    select 中的列名前加上其表名。

    select table1.my_column, table2.my_column
    from table1, table2
    where table1.id = table2.t1_id
    

    但是使用这种方法,您必须使用它们返回的顺序索引而不是它们的名称来读取列。另一个答案提到使用as 来命名每一列,所以如果你要按名称阅读它们,请考虑一下。

    【讨论】:

      【解决方案3】:

      当查询连接超过 2 个表而导致列名冲突时,您不能使用*。您可以使用:

      SELECT table_1.*, 
             table_2.*
        FROM table_1, 
             table_2
      

      如果这没有返回您想要的列列表,您将必须明确列出每一列。没有办法 - 这是一个全有或全无的交易。

      表格别名

      ...但是每次都输入完整的表名可能会很痛苦,这就是您可以给表起别名的原因:

      SELECT t1.*, 
             t2.*
        FROM table_1 AS t1, 
             table_2 t2
      

      支持任一别名表示法。如果您想将表连接到自身,它们也是必需的。

      【讨论】:

        【解决方案4】:

        在选择列表中只使用你实际需要的列名总是最好的,但是当你想要所有东西时,那么,继续使用 *:

        Select a.*, 
               b.*, 
               a.id as a_id, 
               b.id as b_id,
               a.name as a_name,
               b.name as b_name
          from tablea a,
               tableb b
        ...
        

        冗余并没有什么坏处,因为 a.* 包括 a_id 和 a_name,但是来自 * 的值会在关联数组中丢失,所以只需将它们用新的唯一名称放回去。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-14
          • 2015-01-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多