使用连接在MySQL查询中苦苦挣扎

时间:2010-07-19 13:06:07

标签: mysql join

我有3个表来存储有关书籍的信息:

books
-----
id
title

authors
-------
id
name

books_to_authors
----------------
book_id
author_id

当显示书籍的信息时,我希望能够选择同一作者的任何其他书籍。

我从第一个查询中获得了当前的书籍ID,但我无法弄清楚从哪里开始实现我需要的,因为可能有多个作者。显然只有其中一个就很简单,所以我真的很挣扎。任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:1)

我认为应该这样做。只需将?替换为他们当前正在查看的图书ID,这将为您提供同一作者的所有图书。

SELECT b.*
FROM books b
INNER JOIN books_to_authors b2a ON b2a.book_id = b.id
WHERE b2a.author_id IN (
  SELECT author_id FROM books_to_authors WHERE book_id = ?
)

如果您要排除他们当前正在查看的图书,您可以更改此查询:

SELECT b.*
FROM books b
INNER JOIN books_to_authors b2a ON b2a.book_id = b.id
WHERE b2a.author_id IN (
  SELECT author_id FROM books_to_authors WHERE book_id = ?
)
AND b.id <> ?

答案 1 :(得分:0)

$book_id = (your code for retrieving book_id);    

$db_query = "SELECT b.*
FROM books b
INNER JOIN books_to_authors bta ON bta.book_id = b.id
WHERE bta.author_id IN (
  SELECT author_id FROM books_to_authors WHERE book_id = ".$book_id."
)";

我推测你正在使用php。如果我错了,只需使用SQL查询字符串,并忽略其余的...

答案 2 :(得分:0)

您正在寻找下面的查询。我看到一些子查询的解决方案,我强烈建议不要使用子查询。它们比运行2个查询要慢:

  1. 拥有图书ID ,您可以SELECT author_id FROM books_to_authors WHERE book_id = '{$book_id}'
  2. 获取作者ID ,然后运行:

    SELECT books.id, books.title, authors.name FROM books RIGHT JOIN books_to_authors ON books_to_authors.book_id = books.id) RIGHT JOIN authors ON (authors.id = books_to_authors.author_id) WHERE authors.id = '{$author_id}'