Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
10.0k views
in Technique[技术] by (71.8m points)

sql - Inner Joining the same table multiple times

So I have received this error: #1066 - Not unique table/alias: 'Purchase'

I am trying to do the following:

    SELECT Blank.BlankTypeCode
          ,Blank.BlankCode
          ,Payment.Amount
          ,Payment.Type
          ,Purchase.PurchaseDate
          ,Payment.DatePaid
FROM Blank
INNER JOIN Ticket
ON Blank.BlankCode = Ticket.Blank_BlankCode
INNER JOIN MCO_Blank
ON Blank.BlankCode = MCO_Blank.Blank_BlankCode
INNER JOIN Purchase
ON  Ticket.PurchaseID = Purchase.PurchaseID
INNER JOIN Purchase
ON MCO_Blank.PurchaseID = Purchase.PurchaseID
INNER JOIN Payment
ON Ticket.PurchaseID = Payment.PurchaseID
INNER JOIN Payment
ON MCO_Blank.PurchaseID = Payment.PurchaseID
WHERE Payment.Status = "Paid";

Blank Table consists of:

BlankCode,
IssueDate,
Status,
UserID, 
BlankTypeCode

Payment Table consists of:

Type,
Amount,
Status,
DueDate,
PurchaseID,
CurrencyRateDate

Purchase Table consists of:

PurchaseID,
CustomerID,
PurchaseDate,
TotalFare,
TaxAmount,
CurrencyType,
Purchasecol

Ticket Table consists of:

Price,
PurchaseID,
Blank_BlankCode,
Blank_BlankTypeCode,
TicketType,
Airline_Name

MCO_Blank Table consists of:

Service,
Cost,
Description,
Purchase_PurchaseID,
Blank_BlankCode,
Blank_BlankTypeCode

I am unsure of how I can make this work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to use table aliases. You have mentioned the same table more than once in the from clause. The query is something like this:

SELECT b.BlankTypeCode, b.BlankCode, pa1.Amount, pa1.Type, p1.PurchaseDate, pa2.DatePaid
FROM Blank b
INNER JOIN Ticket t
ON b.BlankCode = t.Blank_BlankCode
INNER JOIN MCO_Blank mb
ON b.BlankCode = mb.Blank_BlankCode
INNER JOIN Purchase p1
ON  t.PurchaseID = p1.PurchaseID
INNER JOIN Purchase p2
ON mb.PurchaseID = p2.PurchaseID
INNER JOIN Payment pa1
ON t.PurchaseID = pa1.PurchaseID
INNER JOIN Payment pa2
ON mc.PurchaseID = pa2.PurchaseID
WHERE pa1.Status = "Paid";

I had to make a guess at which payment and purchase is intended for the aliases. These may not be correct in the from and where clauses.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...