Is it possible to retrieve an object that is split into three tables with only one query?

我是研究僧i 提交于 2019-12-25 03:47:16

问题


EDIT: The answers works, but slow down the query a lot. Is there another solution?


I have the following object in my program.

Page haves various TextBlock that haves various Token.

The three are stored in the database in three tables with the same namas of the objects.

I want to know if is possible to recover all the data needed to fill the object in the program with only one query.

I want only one query because I'm using a CURSOR to iterate over all the objects stored in the database.

The database scheme is this:

Page(id, someAttributes)
TextBlock(id,pageId, someAttributes)
Token(textblockId, someAttributes)


回答1:


Assuming that every Page has at least one Textblock with at least one Token each try

SELECT * FROM
Page AS P 
INNER JOIN TextBlock T ON T.pageId = P.id 
INNER JOIN Token TK ON TK.textblockId = T.id;

Alternatively (old syntax):

SELECT * FROM
Page AS P, TextBlock T, Token TK WHERE 
T.pageId = P.id AND
TK.textblockId = T.id;

IF it is possible that the above condition is not always true then you need to use OUTER JOIN instead of INNER JOIN.




回答2:


Yes it is possible with a 3 way join.

You'll get one row per Token in this case.

So you'll need to loop and fetch all rows from the cursor and appropriately create the objects as you see new Page ids, TextBlock ids, etc.

NOTE: You'll need to use outer joins, in case a TextBlock has no Tokens, so the TextBlock would still be retrieved (with null values for Token attributes). Same for Pages with no TextBlock.




回答3:


Select 
   Page.someAttributes,
   TextBlock.someAttributes,
   Token.someAttributes
From
   Page,
   TextBlock,
   Token
Where 
   Page.id = TextBlock.pageId
AND
   TextBlock.id = Token.textblockId
Group By 
   Page.id


来源:https://stackoverflow.com/questions/7200134/is-it-possible-to-retrieve-an-object-that-is-split-into-three-tables-with-only-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!