[英]Gobbly php to usable SQL?
So I need help converting PHP to SQL. 所以我需要帮助将PHP转换为SQL。 This is the current code (not mine) and it runs three while loops that end up taking about two and a half minutes to run. 这是当前代码(不是我的代码),它运行三个while循环,最终需要大约两分半钟才能运行。 Obviously, not very efficient. 显然,效率不是很高。 I also know that it's the old mysql usage and not the newer mysqli or PDO version.. 我也知道这是旧的mysql用法,而不是较新的mysqli或PDO版本。
Here's a fiddle for the sample data: 这是样本数据的小提琴:
http://sqlfiddle.com/#!2/71c74 http://sqlfiddle.com/#!2/71c74
Looking at the php, I think that this is the query (using SQL). 看着php,我认为这是查询(使用SQL)。
SELECT z.siteID, us.id FROM groups g, usertogroup u, users z, usertosite us
WHERE g.entityID=$thisEntity
and u.groupID=2093 and z.id=userID
and site_id=3411 and user_id=$uid;
(Replaced with real values). (替换为实际值)。
But that returns 1000+ rows when the query should only return 44. So here's the PHP, anyone know what the real query should look like, or maybe a nicer way to write this in PHP? 但这会在查询只返回44时返回1000+行。那么这就是PHP,有人知道真正的查询应该是什么样子,或者也许是用PHP编写此查询的更好方法? The $uid is pulled from the superglobal $_SESSION variable, so it's been set. $ uid是从超全局变量$ _SESSION中拉出的,因此已被设置。 Same with $thisEntity, also pulled from a session variable. 与$ thisEntity相同,也从会话变量中提取。
$site_list3 = array();
$sql_str = "SELECT id FROM groups WHERE entityID=$thisEntity";
$sql_res = mysql_query($sql_str);
$row = mysql_fetch_array($sql_res, MYSQL_ASSOC);
while ($row) {
$passed = 1;
$sql_str2 = "SELECT siteID FROM usertogroup u,users z where groupID=" . $row['id'] . " and z.id=userID;";
$sql_res2 = mysql_query($sql_str2);
$row2 = mysql_fetch_array($sql_res2, MYSQL_ASSOC);
while ($row2) {
if ($thisEntity == 1761 && $row2['siteID'] == 3411) {
} else {
$sql_str3 = "SELECT id FROM usertosite WHERE site_id=" . $row2['siteID'] . " and user_id=$uid";
$sql_res3 = mysql_query($sql_str3);
$row3 = mysql_fetch_array($sql_res3, MYSQL_ASSOC);
if (!$row3)
$passed = 0;
}
$row2 = mysql_fetch_array($sql_res2, MYSQL_ASSOC);
}
if ($passed == 1)
{
$site_list3[] = (int) $row['id'];
}
$row = mysql_fetch_array($sql_res);
}
$site_list3_values = implode(", ", $site_list3);
It looks like you're missing one or more JOIN clauses. 似乎您缺少一个或多个JOIN子句。 Without a working schema, I can only guess... But does this work? 没有有效的方案,我只能猜测...但这行得通吗?
SELECT
U.siteID,
US.id
FROM
groups G
JOIN usertogroup UG ON(UG.groupID=G.id) -- was missing?
JOIN users U ON(U.id=U.userID)
JOIN usertosite US ON(US.user_id=U.id) -- was missing?
WHERE
G.entityID = 12345
AND US.site_id = ABCDEF
AND ....
Where possible, I personally prefer "ON" conditions to "WHERE" expressions, because I think it makes the relationships between tables more evident. 在可能的情况下,我个人更喜欢“ ON”条件而不是“ WHERE”表达式,因为我认为它使表之间的关系更加明显。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.