查询没有产生它应该的东西

时间:2016-08-23 09:47:05

标签: sql sqlite

我有以下两个表:

表作者:

AuthorID  Name
A         John
B         Alex
C         Carl

表AuthorsCompatibility:

AuthorID1    AuthorID2    Compatibility
A            B            5.0
A            C            4.0
B            C            4.5

我想制作以下内容:

AuthorID1   Name1    AuthorID2   Name2   Compatibility
A           John     B           Alex    5.0
A           John     C           Carl    4.0
B           Alex     C           Carl    4.5

这是我尝试过的,但我知道它不起作用:

select AuthorID1, A.Name, AuthorID2, B.Name, Compatibility
from AuthorsCompatibility, Authors as A, Authors as B
where AuthorID1=A.AuthorID and AuthorID2=B.AuthorID

4 个答案:

答案 0 :(得分:4)

SELECT ac.AuthorID1, a.Name, ac.AuthorID2, b.Name, ac.Compatibility
FROM AuthorsCompatibility ac
INNER JOIN AUTHORS a ON ac.AuthorID1 = a.AuthorID
INNER JOIN AUTHORS b ON ac.AuthorID2 = b.AuthorID

答案 1 :(得分:2)

您未正确加入(您正在使用非常旧的联接)。尝试下面的连接;

SELECT
    ac.AuthorID1
    ,a1.Name AS Name1
    ,ac.AuthorID2
    ,a2.Name AS Name2
    ,ac.Compatibility
FROM AuthorsCompatibility ac
INNER JOIN Authors a1
    ON ac.AuthorID1 = a1.AuthorID
INNER JOIN Authors a2
    ON ac.AuthorID2 = a2.AuthorID

使用此样本数据;

CREATE TABLE Authors (AuthorID nvarchar(1), Name nvarchar(10))
INSERT INTO Authors
VALUES
('A', 'John')
,('B', 'Alex')
,('C', 'Carl')

CREATE TABLE AuthorsCompatibility (AuthorID1 nvarchar(1), AuthorID2 nvarchar(1), Compatibility money)
INSERT INTO AuthorsCompatibility (AuthorID1, AuthorID2, Compatibility)
VALUES
('A', 'B', 5.0)
,('A', 'C', 4.0)
,('B', 'C', 4.5)

给出这个结果;

AuthorID1   Name1   AuthorID2   Name2   Compatibility
A           John    B           Alex    5.00
A           John    C           Carl    4.00
B           Alex    C           Carl    4.50

答案 2 :(得分:2)

您可以像JOT格式一样重写它

select ac.AuthorID1, A.Name, ac.AuthorID2, B.Name, ac.Compatibility
  from AuthorsCompatibility ac
  join Authors as A
    on ac.AuthorID1 = A.AuthorID
  join Authors as B
    on ac.AuthorID2 = B.AuthorID

答案 3 :(得分:0)

我已经尝试了您的查询,但它运作正常:

CREATE TABLE #Authors (AuthorID nvarchar(1), Name nvarchar(10))
INSERT INTO #Authors
VALUES
('A', 'John')
,('B', 'Alex')
,('C', 'Carl')

CREATE TABLE #AuthorsCompatibility (AuthorID1 nvarchar(1), AuthorID2 nvarchar(1), Compatibility money)
INSERT INTO #AuthorsCompatibility (AuthorID1, AuthorID2, Compatibility)
VALUES
('A', 'B', 5.0)
,('A', 'C', 4.0)
,('B', 'C', 4.5)

select 
    AuthorID1, A.Name, AuthorID2, B.Name, Compatibility
from #AuthorsCompatibility, #Authors as A, #Authors as B
where AuthorID1=A.AuthorID and AuthorID2=B.AuthorID

drop table #AuthorsCompatibility,#Authors