Sql 将表与其自身连接起来

Sql 将表与其自身连接起来,sql,oracle,sqlplus,Sql,Oracle,Sqlplus,我想把一张桌子和它自己连接起来 但是得到以下错误 SQL> select a.bookid, b.auname 2 from book_author a, book_author b 3 where a.bookid = b.auname; where a.bookid = b.auname * ERROR at line 3: ORA-01722: invalid number 我尝试加入的表是: create table book_author (Aun

我想把一张桌子和它自己连接起来

但是得到以下错误

SQL> select a.bookid, b.auname
2  from book_author a, book_author b
3  where a.bookid = b.auname;
where a.bookid = b.auname
             *
ERROR at line 3:
ORA-01722: invalid number
我尝试加入的表是:

create table book_author
(Auname varchar2(15),
bookid number(5),
对于每个bookid,我想列出bookid和每个作者(第2列)以及他/她的合著者(第3列) 我想用作者的书的虚拟副本来做这件事。 我期望的输出如下所示

Bookid       Author  Coauthor
1101         Dilbert Emerson
1101         Dilbert Sartre
1101         Emerson Dilbert
1101         Emerson Sartre
1101         Sartre  Dilbert
1101         Sartre  Emeson

    (note Dilbert Dilbert should not appear)



SQL> select * from book_author
2  order by bookid;

AUNAME              BOOKID
--------------- ----------
Emerson               1101
Sartre                1101
Dilbert               1101
Sartre                1102
Axel                  1102
Marquez               1103
Breese                1103
Young                 1104
Groom                 1104
Young                 1105
Blake                 1105
Julian                1105
Verde                 1105
Scott                 1105
Black                 1106
Sartre                1106
Simon                 2007
Emerson               2007
Pell                  2007
Rogers                2008
Sartre                2008
Codd                  2008
Young                 2008
Lamont                2010
Fellows               2011
Modiano               2011
Poe                   2222
Modiano               2222
Null                  2229

如果希望加入
bookid
上的表,则不希望将
bookid
(数字列)与
auname
(字符串列)进行比较

差不多

select a.bookid, a.auname, b.auname
  from book_author a, 
       book_author b
 where a.bookid = b.bookid
   and a.auname != b.auname;

贾斯汀·凯夫得到了正确的答案。作为补充:ORA-01722:invalid number表示在一个表达式中混合了number和varchar列。如果您没有明确说明您想要什么,Oracle将使用隐式转换规则。在本例中,Oracle尝试将b.auname转换为number,因为您说过要将其与number值进行比较

通常这是一个错误,但很少是你想要的。如果是这样,您应该明确说明Oracle应该做什么:

where to_char(a.bookid) = b.auname

首先,您试图将
varchar
number
进行比较。。。第二,我只看到两列,什么是“第三列”?如何区分作者和合著者。这只有两列。我已经用我想要的输出格式更新了这个问题。@JacobLindbergSørensen-然后将a.auname添加到选择列表中。我已经更新了我的答案谢谢。我面临的最后一个问题是,我只想看到和我一起工作过的作者像我给出的例子一样配对。现在我得到了所有可能的作者和合著者的组合。非常感谢!非常感谢你的帮助!