使用参数从mysqli_query输出获取单行,不带循环

时间:2017-05-01 16:14:41

标签: php mysql sql

是否有可能从mysqli_fery结果中获取单行{来自mysqli_fetch_array('result_from_mysqli_query'>)}基于特定列的值,而没有循环的帮助?

我是PHP的新手,请告诉我这是否有功能?我正在努力改进用PHP编写的应用程序,该应用程序具有执行大约500秒的复杂查询。查询是这样的:

SELECT distinct(t1.`testName`) AS test1, t1.`className`, t1.`duration`, t1.`id`, t1.`skipped`, t1.`failedSince`, t1.`buildNumber`, t1.`errorStackTrace`, t2.`errorStackTrace` AS E2, t3.`errorStackTrace` AS E3, t4.`errorStackTrace` AS E4, t5.`tester`, t1.`comments`, t2.`comments` AS C2, t2.`buildNumber` AS B2, t3.`comments` AS C3, t3.`buildNumber` AS B3, t4.`comments` AS C4, t4.`buildNumber` as B4, t5.`tester` AS owner, t5.`jira_id`, t6.`occurences`
from
`sample` AS t1
left join `testnametester` as t5 ON t1.`testName` = t5.`testCase`
left join `statsbuilder` as t6 on t1.`testName`= t6.`testName`
left join `sample` as t2 on t1.`testName` = t2.`testName`
left join `sample` as t3 on t1.`testName` = t3.`testName`
left join `sample` as t4 on t1.`testName` = t4.`testName`
where t1.`buildNumber`=500 and t1.`errorStackTrace` IS NOT NULL and t2.`buildNumber`=499 and t3.`buildNumber`=498 and t4.`buildNumber`=497 group by t1.id order by t1.testName desc

现在,为了使这个查询更快,我试图执行t2,t3&的查询。 t4分别从这些查询结果中只取一行与t1的结果(基于testname)匹配,并在打印数据表时使用它。现在,如果我使用循环从t2 / t3 / t4获得与t1的testName匹配的数据,那么复杂性将保持相同。

1 个答案:

答案 0 :(得分:1)

首先,尝试优化查询可能是个好主意。 MySQL在优化自身方面通常比你更好。

查看https://dev.mysql.com/doc/refman/5.7/en/using-explain.html以获取一些解释。基本上,将EXPLAIN放在查询前面,MySQL将向您显示有关如何运行查询的一些信息 - 使用哪些索引等。如果您想要快速查询,您应该在正确的列上添加索引 - 你做完了吗?是什么?

其次,为什么要执行4(加入)查询?你不能只写WHERE t1.buildNumber >= 497 AND t1.buildNumber <= 500吗?

例如:

SELECT distinct(t1.`testName`) AS test1,
       t1.`className`,
       t1.`duration`,
       t1.`id`,
       t1.`skipped`,
       t1.`failedSince`,
       t1.`buildNumber`,
       t1.`errorStackTrace`,
       t1.`comments`,

       -- t5.`tester`, we can remove this one as you're selecting it twice
       t5.`tester` AS OWNER,
       t5.`jira_id`,
       t6.`occurences`,
FROM `sample` AS t1
LEFT JOIN `testnametester` AS t5 ON t1.`testName` = t5.`testCase`
LEFT JOIN `statsbuilder` AS t6 ON t1.`testName`= t6.`testName`
WHERE `t1`.`buildNumber` >= 497
  AND `t1`.`buildNumber` <= 500
  AND `t1`.`errorStackTrace` IS NOT NULL
GROUP BY t1.id
ORDER BY t1.testName DESC