【问题标题】:mysql problem with union/join used in conjunctionmysql的联合/连接问题
【发布时间】:2010-10-24 21:59:41
【问题描述】:

我有这两张表:

表作者:

ID (INTEGER),
author_name (VARCHAR),
first_name (VARCHAR),
last_name (VARCHAR),
preferred_name (VARCHAR)

表共同创作:

ID (INTEGER)
author1ID (INTEGER),
author2ID (INTEGER),
paper_ID (INTEGER) // (ID of the co-authored paper referenced by this link)

如您所见,两个表都有一个“ID”列,但它们不相关。

但是,当我使用这个查询时:

select author_name, count(*) as NumPapers from
(select * from Author as a join CoAuthored as c on a.ID = c.author1ID
union distinct
select * from Author as b join CoAuthored as d on b.ID = d.author2ID) as t1
group by author_name
order by NumPapers;

mySQL 给我一个错误提示:ERROR 1060 (42S21): Duplicate column name 'ID'

为什么会发生这种情况,我该如何避免?

【问题讨论】:

    标签: mysql join union


    【解决方案1】:

    而不是select * ... 在被联合的两个子查询中使用select author_name ...。问题源于 AuthorCoAuthored 都有 ID 列。 SELECT * 带来了这两个列,MySQL 不喜欢将这些合并以生成具有两个同名列的结果集。

    【讨论】:

      【解决方案2】:

      试试这个:

      select author_name, count(*) as NumPapers from 
      (
          select a.id, a.author_name from Author as a 
          join CoAuthored as c on a.ID = c.author1ID
          union distinct
          select b.id, b.author_name from Author as b
          join CoAuthored as d on b.ID = d.author2ID
      ) as t1
      group by author_name
      order by NumPapers;
      

      由于您不需要来自 CoAuthored 的 ID 列,因此您不能在内部查询中选择它。这应该会删除您的重复列错误,因为它只选择了 1 个 ID 列。

      【讨论】:

      • 这解决了问题,但现在 NumPapers 总是返回 1。这是为什么呢?我改用了 Will A 的解决方案,并保留了所有的 union,它似乎工作正常。
      【解决方案3】:

      怎么样:

      SELECT author_name, COUNT(*) AS NumPapers
        FROM Author AS a
        JOIN CoAuthored AS c ON a.ID = c.author1ID OR a.ID = c.author2ID
       GROUP BY author_name
       ORDER BY NumPapers;
      

      【讨论】:

        猜你喜欢
        • 2021-08-13
        • 2016-12-15
        • 1970-01-01
        • 1970-01-01
        • 2014-12-20
        • 1970-01-01
        • 2010-09-23
        • 2011-02-16
        相关资源
        最近更新 更多