使用单个查询从两个子表中检索行

时间:2014-04-01 18:03:05

标签: mysql database

我有3个表:readablesbooksthesesbookstheses表都包含readables表的子项。如你所见:

readables
  - id 
  - title
  - author
  - type

一本或多本书可能具有相同的标题,但它们的电话号码不同而且isbn

books
  - call_number 
  - isbn
  - isarchived
  - edition
  - book_id (references readables.id)

与书籍不同,这些标题是独一无二的

theses
  - panelists
  - adviser
  - isarchived
  - book_id (references readables.id)

在我的代码中,我必须查询两次并将结果组合以实现我想要的输出:

//first query
$bookResult = mysql_query("SELECT id, title, author, call_number, r.type FROM readables r INNER JOIN books b ON r.id=b.book_id
                             WHERE archived='false' AND title LIKE '$searched%' ORDER BY $sort LIMIT $start,$range");

//second query
$thesisResult = mysql_query("SELECT id, title, author, r.type FROM readables r INNER JOIN theses t ON r.id=t.book_id
                               WHERE archived='false' AND title LIKE '$searched%' ORDER BY $sort LIMIT $start, $range");

//combine results
while($book = mysql_fetch_assoc($bookResult)){
  array_push($itemData['items'], $book);
  $itemData['count']++;
}

如何使用单个查询从两个子表中检索行?

0 个答案:

没有答案