Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何重构(或提高性能)重复的子查询_Mysql_Sql_Database - Fatal编程技术网

Mysql 如何重构(或提高性能)重复的子查询

Mysql 如何重构(或提高性能)重复的子查询,mysql,sql,database,Mysql,Sql,Database,(这是对这个问题的跟进:) 我怎样才能把这样的东西做得更好 (select * from tableOne A, tableTwo B where ~) union (select * from tableTwo) 特例 表一 它与我朋友的userNum列表一起返回 我使用的 表二 它返回我朋友的朋友的用户名列表。您可以看到表二使用表一作为表C 然后我想像这样得到我朋友的userNum和朋友的userNum 表三 最后,我将使用TableThree获取那些不是我朋友的朋友的人的用户名 sele

(这是对这个问题的跟进:)

我怎样才能把这样的东西做得更好

(select * from tableOne A, tableTwo B where ~) union (select * from tableTwo)
特例 表一

它与我朋友的userNum列表一起返回

我使用的

表二

它返回我朋友的朋友的用户名列表。您可以看到表二使用表一作为表C

然后我想像这样得到我朋友的userNum和朋友的userNum

表三

最后,我将使用TableThree获取那些不是我朋友的朋友的人的用户名

select A.userNum from users A where A.userNum NOT IN TableThree;
您可以看到TableThree在查询中两次使用子查询TableOne。我认为这是一个坏主意,因为在糟糕的重构和糟糕的性能中


是否有更好的方法编写此查询?

旁注:编写更好的SQL代码的提示提示1使用有用的别名而不是表1的别名B用于表2。。。使您很难理解QuerysTip2使用ANSI连接语法。。TIP3结构(换行符、制表符)使您的SQL可读,而不是单行线。。明白我的意思了吗,这比你的SQL更具可读性。这个查询在你的系统上执行得真的很糟糕吗?你想优化它吗?或者你只相信它可能表现不佳,这只是一个学术问题?在第一种情况下,请提供查询的确切SQL代码,并解释计划和表结构以及现有索引的定义。在后一种情况下,这个问题相当主观,很难回答——在某些情况下,UNION比一个具有许多OR条件的大型查询性能更好,但在其他情况下,情况可能恰恰相反。@kordirko我认为这是第一种情况。最后一次查询(表3)所需的时间约为0.219秒。使用查询(TableThree)作为where caluse中的子查询,我必须检索100条记录(稍后我将用我正在尝试的操作编辑我的问题)。这大约需要0.7秒。我不知道这对于具有10K行的数据库是否正常。稍后我将编辑此问题并提供更多信息。
select A.userNum from users A, addressbook B, 
(select A.userNum from users A, addressbook B where B.userNum=1 and B.phone=A.phone) C 
where C.userNum=B.userNum and A.phone=B.phone;
TableOne union TableTwo;
select A.userNum from users A where A.userNum NOT IN TableThree;