2

我有这个查询:

SELECT Book.title, Book.copyright, Book.publisher, Book.id,
    MaterialType.type, Item.id as item_id, 100 as relevance FROM `books` AS `Book`
inner JOIN `material_types` AS `MaterialType` ON (`MaterialType`.`id` = `Book`.`material_type_id`)
inner JOIN `items` AS `Item` ON (`Item`.`book_id` = `Book`.`id` AND `Item`.`accession_number` = '0936')
WHERE 1 = 1  GROUP BY `Book`.`id`

什么都没有。但是,如果我执行此查询,它会找到正确的记录:

SELECT * FROM `items` AS `Item` WHERE `Item`.`accession_number` = '0936'

不过,最奇怪的部分是它适用于其他记录。如果我使用 accession_number 0396,如果在两个查询中都找到正确的记录。我无法为我的生活弄清楚发生了什么。任何帮助是极大的赞赏。

4

2 回答 2

1

您需要将 LEFT JOIN 与 matierial_types 一起使用,因为此表可能没有与书籍相同的 materialType id 试试这个

SELECT Book.title, Book.copyright, Book.publisher, Book.id,
    MaterialType.type, Item.id as item_id, 100 as relevance FROM `books` AS `Book`
LEFT JOIN `material_types` AS `MaterialType` ON (`MaterialType`.`id` = `Book`.`material_type_id`)
LEFT JOIN `items` AS `Item` ON (`Item`.`book_id` = `Book`.`id`) 
WHERE `Item`.`accession_number` = '0936'
GROUP BY `Book`.`id`
于 2012-05-13T17:02:05.047 回答
0

看起来您在“Book”中没有与“accession_number”为 0936 的项目相对应的条目。对项目的右连接应该显示:

SELECT Book.title, Book.copyright, Book.publisher, Book.id,
    MaterialType.type, Item.id as item_id, 100 as relevance FROM `books` AS `Book`
left JOIN `material_types` AS `MaterialType` ON (`MaterialType`.`id` = `Book`.`material_type_id`)
right JOIN `items` AS `Item` ON (`Item`.`book_id` = `Book`.`id` AND `Item`.`accession_number` = '0936')
WHERE 1 = 1  GROUP BY `Book`.`id`
于 2012-05-13T17:07:18.080 回答