mysql循环查找sql_循环中的MySQL查询与使用SQL连接

bd96500e110b49cbb3cd949968f18be7.png

I'm having an inner debate at my company about looping queries in this matter:

$sql = "

SELECT foreign_key

FROM t1";

foreach(fetchAll($sql) as $row)

{

$sub_sql = "

SELECT *

FROM t2

WHERE t2.id = " . $row['foreign_key'];

foreach(fetchAll($sub_sql) as $sub_row)

{

// ...

}

}

Instead of using an sql join like this:

$sql = "

SELECT t2.*

FROM t2

JOIN t1

ON t1.foreign_key = t2.id";

foreach(fetchAll($sql) as $row)

{

// ...

}

Additional information about this, the database is huge, millions of rows.

I have of course searched an answer to this question, but nobody can answer this in a a good way and with a lot of up votes that makes me certain that one way is better then the other.

Question

Can somebody explain to me why one of thees methods is better then the other one?

解决方案

The join method is generally considered better, if only because it reduces the overhead of sending queries back and forth to the database.

If you have appropriate indexes on the tables, then the underlying performance of the two methods will be similar. That is, both methods will use appropriate indexes to fetch the results.

From a database perspective, the join method is far superior. It consolidates the data logic in one place, making the code more transparent. It also allows the database to make optimizations that might not be apparent in application code.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值