简体   繁体   English

PHP / MySQL结合两个查询以减少循环

[英]PHP/MySQL Combining two queries to reduce loop

I have the following query, whos results then loop out to run another query and retrieve another set of results, but I would like to combine these so I am not running so many queries and to speed everything up, but I've tried a few iterations and either get null results, or errors with the syntax. 我有以下查询,谁的结果然后循环出去以运行另一个查询并检索另一组结果,但是我想将它们组合在一起,所以我没有运行太多的查询并加快了所有的速度,但是我尝试了一些迭代,或者得到结果,或者语法错误。 So looking for some community magic here. 因此,在这里寻找一些社区魔术。

Query 1: 查询1:

SELECT tou_tracking_start, tou_tracking_end, tou_tracking_timestart,
tou_tracking_timeend, tou_tracking_units, daytype_ID 
FROM db_tou_tracking 
WHERE ICP_ID = '39' 
AND (tou_tracking_start >= '2013-01-01' AND tou_tracking_end <= '2013-12-31')

Which loops out its results and are then used in the next query: 哪个循环出结果,然后在下一个查询中使用:

SELECT rates_tou_rate, rates_tou_PPD FROM db_rates_tou 
WHERE (rates_tou_start <= '" .$tou_tracking_start . 
    "' AND rates_tou_end >= '" . $tou_tracking_end . "') 
AND (rates_tou_timestart <= '" . $tou_tracking_timestart . 
    "' AND rates_tou_timeend >= '" . $tou_tracking_timeend . "') 
AND daytype_ID = ".$tou_tracking_daytype_ID." 
LIMIT 1

If these can be combined, then I only need to select: 如果这些可以组合,那么我只需要选择:

  • tou_tracking_start tou_tracking_start
  • tou_tracking_end tou_tracking_end
  • rates_tou_rate rates_tou_rate
  • rates_tou_PPD rates_tou_PPD

Many thanks in advance for the help with this. 在此先非常感谢您的帮助。

I would use a JOIN 我会用JOIN

SELECT tt.tou_tracking_start, tt.tou_tracking_end, rt.rates_tou_rate, rt.rates_tou_PPD
FROM db_tou_tracking tt
JOIN db_rates_tou rt ON rt.daytypeID = tt.daytype_ID
AND (tt.tou_tracking_start >= '2013-01-01' AND tt.tou_tracking_end <= '2013-12-31')

tt is an alias for db_tou_tracking and rt is an alias for db_rates_tou. tt是db_tou_tracking的别名,而rt是db_rates_tou的别名。

I assume they are matched by daytype_ID in both tables and there is a 1 to 1 relationship. 我假设它们在两个表中都由daytype_ID匹配,并且存在1对1的关系。

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

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