2013-06-27 188 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'已经逃脱了。 –