gpt4 book ai didi

Php & Mysql,从PHP-for循环中过滤出子查询进入MySQL语句

转载 作者:行者123 更新时间:2023-11-29 00:51:24 25 4
gpt4 key购买 nike

我必须修改连接到极其困惑的数据库设计的 PHP 脚本。解释问题的最好方法是发布代码,我将在其中通过代码块内的注释来描述发生了什么。加上简短的介绍:

短篇小说:
1.) 有一个“mainQuery”,在显示其数据的 for 循环内有 3 个嵌套子查询。
2.) 所有三个子查询都需要 main_table_ID 才能计算每个 fetched_row 的出现次数。

我想要什么:
1.) 一个优化的 mainQuery,它自己单独计算一个 id 的 3 次出现。
2.) 因此在 for 循环中根本没有子查询。

我通过优化 mainQuery 已经取得的成果:
1.) 我可以一次过滤一个子查询,参见语句:

SELECT
main_table.id_col,
count(table_1.a_col) AS count_1,
main_table.a_col,
main_table.b_col,
main_table.c_col,
main_table.d_col,
main_table.e_col

FROM main_table
LEFT JOIN
table_1
ON
table_1.a_col = main_table.id_col
GROUP BY
main_table.id_col

但是当我为 for 循环内的其他嵌套语句之一添加另一个 LEFT JOIN 时,该语句对所有内容求和,count_1 到 count_3 看起来相同。

现在包含子查询和 for 循环的代码块:

<?php
$mainQuery = "SELECT
main_table.id_col,
main_table.a_Col,
main_table.b_Col,
main_table.c_col,
main_table.d_col,
main_table.e_col
FROM
main_table";

$mainQueryResult = mysql_query($mainQuery);
$mainQueryRows = mysql_num_rows($mainQueryResult);

for($j = 0 ; $j < $mainQueryRows ; ++$j){
//mainQuery data
$mainQueryRow = mysql_fetch_row($mainQueryResult);
$main_table_ID = $mainQueryRow[0];

//first subquery, can be filtered out one at a time
//using introductory-statement
$count_1_subQuery = "SELECT * FROM table_1
WHERE table_1.id_col = '$main_table_ID'";
//first subquery-count of rows with matching id
$count_1 = mysql_num_rows(mysql_query($count_1_SubQuery, $connection));

//second subquery
$count_2_subquery = "SELECT * FROM table_2
WHERE table_2.id_col = '$main_table_ID'";
//second subquery-count of rows with matching id
$count_2 = mysql_num_rows(mysql_query($count_2_subQuery, $connection));

//third subquery
$count_3_subquery = "SELECT * FROM table_3
WHERE table_3.id_col = '$main_table_ID'";
//third subquery-count of rows with matching id
$count_3 = mysql_num_rows(mysql_query($count_3_subQuery, $connection));

//Fill Table with count_1 to count_3
//and main_table.a_col to main_table.e_col
//no problems here
}
?>

我希望我能足够清楚地解释这个问题,我也希望你们中的一个人能帮助我,如果他/她能为这样的问题分配时间的话。

最佳答案

首先在子查询中GROUP BY,然后JOIN到主表:

SELECT  
m . id_col
, g1 . count_1
, g2 . count_2
, g3 . count_3
, m . a_col
, m . b_col
, m . c_col
, m . d_col
, m . e_col
FROM
main_table AS m
LEFT JOIN
( SELECT id_col
, COUNT(*) AS count_1
FROM table_1
GROUP BY id_col
) AS g1
ON g1.id_col = m.id_col
LEFT JOIN
( SELECT id_col
, COUNT(*) AS count_2
FROM table_2
GROUP BY id_col
) AS g2
ON g2.id_col = m.id_col
LEFT JOIN
( SELECT id_col
, COUNT(*) AS count_3
FROM table_3
GROUP BY id_col
) AS g3
ON g3.id_col = m.id_col

关于Php & Mysql,从PHP-for循环中过滤出子查询进入MySQL语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8429883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com