MySQL JOIN全选

时间:2015-08-02 14:34:12

标签: mysql sql

我有以下表格:

图书

book_id | book_name | book_photo

专栏

rubric_id | rubric_name

作者

author_id | first_name | last_name

BOOK_RUBRIK

book_id | rubric_id

BOOK_AUTHOR

book_id | author_id

我想像这样选择JOIN:

SELECT 
  book.book_name, 
  autor.first_name, 
  autor.last_name, 
  rubric_rubric_name 
FROM book 
  INNER JOIN book_autor ON book.book_id = autor_id 
  LEFT JOIN book_rubric ON book.book_rubric = rubric_id 
ORDER BY book.book_id;

但它不起作用。如何选择book_name,rubric_name,first_name和_last_name?

2 个答案:

答案 0 :(得分:1)

您错过了一个表authors,因此您无法提取有关作者的数据:

SELECT 
  book.book_name, 
  autor.first_name, 
  autor.last_name, 
  rubric_rubric_name 
FROM book 
  INNER JOIN book_autor ON book.book_id = book_autor.book_id 
  INNER JOIN author ON book_autor.autor_id = autor.autor_id 
  LEFT JOIN book_rubric ON book.book_rubric = rubric_id 
ORDER BY book.book_id;

添加INNER JOIN book_autor ON book.book_id = book_autor.book_idINNER JOIN author ON book_autor.autor_id = autor.autor_id代替INNER JOIN book_autor ON book.book_id = autor_id将解决问题。

修改

我错过了作者脚本中名称中存在一些错误的事实。我修复了选择。这是第一个:

您的表格结构:

BOOK
  book_id 
  book_name 
  book_photo

RUBRIC
  rubric_id 
  rubric_name

AUTHOR
  author_id 
  first_name 
  last_name

BOOK_RUBRIK
  book_id 
  rubric_id

BOOK_AUTHOR
  book_id 
  author_id

您的选择语句:

SELECT 
  b.book_name, 
  a.first_name, 
  a.last_name, 
  br.rubric_name 
FROM 
  BOOK AS b 
  INNER JOIN BOOK_AUTHOR ba ON b.book_id = ba.book_id 
  INNER JOIN AUTHOR a ON ba.author_id = a.author_id 
  LEFT JOIN BOOK_RUBRIK br ON b.book_id = br.book_id 
ORDER BY 
  b.book_id;

答案 1 :(得分:0)

select book.book_name, author.first_name, author.last_name, rubric.ruburic_name
from book
    inner join book_author on book.book_id = book_author.book_id
    inner join author on book_author.author_id = author.author_id
    inner join book_rubric on book.book_id = book_rubric.rubric_id
    inner join rubric on book_rubric.rubric_id = rubric.rubric_id
order by book.book_id