2013-06-27 186 views
0

我有一個order表像這樣SQL查詢來連接表

id | bookId | bookAuthorId 
-------------------------- 
1  3   2  
2  2   1   
3  1   2   

和另一個表

bookId | book 
--------------- 
    1  bookA 
    2  bookB 
    3  bookC 

bookAuthorId | author 
------------------------ 
    1    authorA 
    2    authorB 

我想從order表,其中id = 1獲取記錄結果集像這樣

id | book | author 

我的嘗試:

select * from order 
join bookId,bookAuthorId 
    on order.bookId = books.bookId 
     and order.authorId = authors.authorId 

我不知道如何加入這些表,以獲得所需result.How我能做到這一點?

回答

2

您可以使用where條款做

select 
    id, book, author 
from 
    `order`, book, author 
where 
    `order`.bookId = book.bookId 
    and 
    `order`.authorId = author.authorId 

或者

select 
    o.id, b.book, a.author 
from 
    `order` o 
natural join 
    book b 
natural join 
    author a 
+0

-1用於顯示SQL反模式的隱式連接。我們不應該教人們使用這種非常糟糕的SQL形式。 – HLGEM

+0

一個人應該知道所有人,而且應該知道爲什麼一個人比另一個人更好 – darijan

+0

不應該學習隱式聯接作爲初學者。直到你理解了連接,你纔會知道它們存在。 – HLGEM

2
select `order`.id, book.book, author.author 
from `order` 
join book on (`order`.bookId = book.bookId) 
join author on (author.bookAuthorId = book.bookId) 
where `order`.id = 1; 

假設bookAuthorId可以鏈接到BOOKID,否則,你將需要添加一個外鍵。

+0

'order'是SQL中的關鍵字。你需要逃避它。 –

+0

@DavidStarkey固定,謝謝。 – Igor

3
select o.id, b.book, a.author 
from 'order' o 
join book b on o.bookid=b.bookid 
join author a on o.bookauthorid=a.bookauthorid 
where o.id=1 
+1

大衛是對的,命令是一個關鍵字,應該被轉義 –

+0

除別名外,這與GrailsGuy的答案相同。只有他纔會真正的工作,因爲'other'已經逃脫了。 –