我可以使用索引提高此请求的效率吗?

时间:2015-06-19 16:29:30

标签: java mysql sql jpa

我有这个bean / table“Userinfo”,其中包含列id,用户名和twitchChannel。 对于大多数userinfo,twitchChannel列将为null。我正在遍历表中的每个userinfo实体并搜索twitchChannel列,如果列不为null,我将twitchChannel放入数组中。

这就是我的要求:

"SELECT ui FROM Userinfo ui WHERE ui.iduserinfo=:id"

这是非常低效的,因为我经历了每个单独的实体,即使那些具有null twitchChannel的实体,我也不感兴趣。

这是java,但我对每一行进行了评论,因此对于那些不了解它的人来说很容易理解。

    while (true) { // I'm going through the table in an infinite loop
        int id = 0; //id that is incremented for searches
        Userinfo ui;  // this will be an object that will hold the result of my query
        do {
            ui = ups.getUserInfo(id); // this execute the query I posted above
            id++; //incrementing id for next search
            if (ui.getTwitch() != null) {  // if the search didn't return null
                twitchChannels.add(ui.getTwitch());   // put my twitch in an array
            }
        } while (ui != null);
    }

所以目前我正在经历表格中的每个实体,即使是那些有零抽搐的实体。根据我的理解,可以使用索引加快流程。

CREATE INDEX twitchChannel
ON Userinfo (twitchChannel)

所以类似的东西会有一个没有null twitchChannel的表。我如何像上面一样循环这个表? 它是否与java持久性一样工作?

2 个答案:

答案 0 :(得分:1)

如果我理解你的问题。你有一个包含数字ID的表。你正在搜索实数的空格,看看是否有任何一个与你表中的id相对应('twitch'id?)

假设你的用户数不足,我认为你可以改变这种逻辑。

将您的查询更改为:

SELECT iduserinfo FROM Userinfo ORDER BY iduserinfo

然后你的java代码将是:

   uiResult = ups.getUserInfo(id); // this executes the new query
   while (uiResult.next()) {
        twitchChannels.add(uiResult.getTwitch());   // put my twitch in an array
    }

(道歉,自从我使用jdbc以来已经很长时间了。)

抱歉,如果我误解了这个问题。

答案 1 :(得分:1)

将查询更改为:

SELECT ui
FROM Userinfo ui
WHERE twitchChannel IS NOT NULL

这将受益于Userinfo(twitchChannel)上的索引(假设确实填充的值非常少)。至少,即使没有使用索引,这也会减少从数据库传递到应用程序的数据量。

相关问题