简体   繁体   English

由于外键值为空,因此无法从表中获取数据

[英]Not getting data from a table because of null value of foreign key

I am using mysql data table and SQL query for fetching data, I am selecting from two tables joined by one to many and many to one relationship, but if the mapped table is not having any value then I am not getting even the value of the table which I am selecting. 我正在使用mysql数据表和SQL查询来获取数据,我从两个表中进行选择,这些表由一对多和多对一的关系连接在一起,但是如果映射表没有任何值,那么我什至无法获得我选择的表。 But when I am putting foreign key then its working fine and I am data of both table. 但是,当我放置外键时,它的工作正常,我是两个表的数据。

@Query("SELECT LD,REC FROM LayerDetails LD JOIN LD.recipeUser REC")
public List getLayerDetails();

This is my SQL query when recipeUser is null then inspite of having value of Layerdetails I am not getting any values. 这是我的SQL查询,当recipeUser为null时,尽管具有Layerdetails的值,但我没有任何值。

I heaved same problem. 我提出了同样的问题。 I solved it by LEFT JOIN instead simple JOIN . 我通过LEFT JOIN而不是简单的JOIN解决了它。


[INNER] JOIN - Returns only records that match in both tables [INNER] JOIN-仅返回两个表中匹配的记录
FULL JOIN - Returns records in both tables. FULL JOIN-返回两个表中的记录。 If there is no match, the missing side will contain null. 如果没有匹配项,则缺少的一面将为空。
LEFT JOIN - Returns all records from left table, with the matching records in table right (if available). LEFT JOIN-返回左侧表中的所有记录,并在右侧表中返回匹配的记录(如果有)。
RIGHT JOIN - Returns all records from right table, with the matching records in table left (if available). RIGHT JOIN-返回右侧表中的所有记录,并在左侧表中找到匹配的记录(如果有)。

解释维恩图

You can view Visual Representation of SQL Joins for more details. 您可以查看SQL联接的可视表示形式以了解更多详细信息。

This happens because the JOIN here is an inner join (which is the default if you don't use a specific join). 发生这种情况是因为此处的JOIN是内部JOIN (如果您不使用特定JOIN ,则为默认JOIN )。 The inner join iterates over tuples of LayerDetails and RecipeUser . 内部LayerDetailsLayerDetailsRecipeUser元组进行迭代。 However, as the field recipeUser is null in your case, it does not have a tuple for that instance of LayerDetails . 但是,由于在您的情况下字段recipeUsernull ,因此对于LayerDetails实例,它没有元组。 So to also find instances of LayerDetails , which have no recipeUser , you would need to use LEFT JOIN instead. 因此,还要查找没有recipeUserLayerDetails实例, LayerDetails需要改用LEFT JOIN

@Query("SELECT LD,REC FROM LayerDetails LD LEFT JOIN LD.recipeUser REC")
public List getLayerDetails();

If you want to have more information on different JOIN possibilities in JPA, you could have a look at https://www.objectdb.com/java/jpa/query/jpql/from for example. 如果您想了解有关JPA中不同JOIN可能性的更多信息,例如,可以查看https://www.objectdb.com/java/jpa/query/jpql/

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

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