简体   繁体   English

SQL查询不拉记录相同

[英]sql query not pulling records the same

I have this query: 我有这个查询:

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`

which pulls up nothing. 这什么都不拉。 HOWEVER, if i do this query it finds the right record: 但是,如果我执行此查询,它将找到正确的记录:

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

The strangest part though, other records it will work for. 不过,最奇怪的部分是它将适用于其他记录。 if I use the accession_number 0396, if finds the right record in both queries. 如果我使用accession_number 0396,是否在两个查询中找到正确的记录。 I can't for the life of me figure out what is going on. 我一生无法弄清楚发生了什么。 Any help is greatly appreciated. 任何帮助是极大的赞赏。

You need to use LEFT JOIN with matierial_types because it is possible that this table doesn't have the same materialType id of books try this 您需要将LEFT JOIN与matierial_types一起使用,因为此表可能没有相同的book的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`

It looks like you have no entry in 'Book' that corresponds to an item with an 'accession_number' of 0936. A Right Join to Items should reveal this: 您似乎在“书”中没有与“ 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`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM