我有三张my_location1&表my_location2& my_location3。 my_ is Prefix
。 location1 = countrylist。 location2 = statslist。 location3 =城镇名单。在其他表中我有用户列表。现在我想列出所有位置(国家 - 统计 - 城镇)使用树木样式+水族用户在每个国家统计城镇(计数)。 (如何生成这个?)
数据库注:pid& pid1 =国家/地区的ID,pid2 =统计信息的ID
my_location1:
id ++++++ name ++++++ active
my_location2:
id ++++++ pid +++++++ name ++++++ active
my_location3:
id ++++++ pid1 +++++++ pid2 ++++++ name ++++++ active
my_user
id ++++++ name ++++++ location1 ++++++ location2 ++++++ location3 ++++++ active
e.x
Country (print count Of users in this country )
+++++++stats (print count Of users in this stats )
++++++++++++town (print count Of users in this town )
++++++++++++town ( ... )
++++++++++++town ( ... )
++++++++++++town ( ... )
+++++++stats ( ... )
++++++++++++town ( ... )
+++++++stats ( ... )
++++++++++++town ( ... )
++++++++++++town ( ... )
Country1 ( ... )
+++++++stats ( ... )
++++++++++++town ( ... )
++++++++++++town ( ... )
Country2 ( ... )
+++++++stats ( ... )
++++++++++++town ( ... )
++++++++++++town ( ... )
++++++++++++town ( ... )
++++++++++++town ( ... )
...more
感谢您的帮助。
答案 0 :(得分:0)
我没有检查代码,但它应该是这样的:
function getCountries()
{
return mysql_query('SELECT c.*, (COUNT(*) from u WHERE u.location1 = c.id) AS user_count
from countrylist c
LEFT JOIN users u
ON u.location1 = c.id
WHERE c.active = 1'
);
}
function getStats($countryId)
{
return mysql_query('SELECT s.*, (COUNT(*) from u WHERE s.location2 = s.id) AS user_count
from statslist s
LEFT JOIN users u
ON u.location2 = s.id
WHERE s.pid = ' . $countryId
);
}
function getTowns($stateId)
{
return mysql_query('SELECT t.*, (COUNT(*) from u WHERE t.location3 = t.id) AS user_count
from townlist
LEFT JOIN users u
ON u.location3 = t.id
WHERE t.pid2 = ' . $stateId
);
}
echo "<ul>\n";
while ($country = mysql_fetch_assoc(getCountries())) {
echo "<li>" . $country["name"] . "(" . $country["user_count"] . ")\n";
echo "<ul>\n";
while ($state = mysql_fetch_assoc(getStats($country["id"]))) {
echo "<li>" . $state["name"] . "(" . $state["user_count"] . ")\n<ul>\n";
while ($town = mysql_fetch_assoc(getTowns($state["id"]))) {
echo "<li>" . $town["name"] . "(" . $town["user_count"] . ")</li>\n";
}
echo "</ul>\n</li>\n";
}
echo "<ul>\n</li>\n";
}
echo "</ul>\n";
它可以而且应该进一步优化,但希望你能得到这个想法。还请注意你的mysql结构是多余的。