1

难以创建质量和优化 mysql 查询。让我们创建一个包含值的表。

CREATE TABLE flow
(
 US1 varchar(20), 
 US2 varchar(30)
);

INSERT INTO flow
(US1, US2)
VALUES
('rasim', 'tere1'),
('rasim', 'tere2'),
('rasim', 'tere3'),
('rasim', 'tere4'),
('tere1', 'tere5'),
('tere1', 'tere6'),
('tere2', 'tere7'),
('tere3', 'tere8'),
('tere3', 'tere9'),
('tere4', 'tere10'),
('tere5', 'tere11'),
('tere5', 'tere12'),
('tere9', 'tere13'),
('tere9', 'tere14');

我想要达到的目标:

$firstUs = DB::query("SELECT US2 FROM `flow` WHERE US1='rasim'");

while($first = DB::fetch($firstUs)):

$second =(int) // select and count(US2) foreach value where US1 = $first['US2'];

$third =(int) //select and count(US2) foreach value where US1 = $second['US2'];

$four = (int) //select and count(US2) foreach value where US1 = $third['US2'];

endwhile;

$firstUs = 返回 4 个值( tere1, tere2, tere3, tere4 )。我希望脚本计算这些值中的每一个,即来自 US1 的条目数。$second = 返回 2 个值( tere5, tere6 )。在第一个 php while 循环中,计数值为 (2)。如何创建一个好的 mysql 脚本以便它可以工作,如果有很多用户访问这个页面,服务器不会崩溃并且查询速度会低得多。

谢谢

我正在努力实现金字塔计划。其中“rasim”是主要用户名。其中 $second 、 $third 和 $four 是每个级别的 int 用户数。$second 将计算金字塔第二层的所有用户。

示例图像它的外观。http://silverstream.ee/img/stack.PNG

4

2 回答 2

0

我认为它是这样的:

select f2.us1, count(f2.us2)
from flow f1
inner join flow f2
f1.us2=f2.us1
where f1.us1='rasim'
group by f2.us1

我希望这是你想要的。

于 2012-10-11T12:38:45.270 回答
0

我认为这里最好的选择是将数据分解成单独的表,这样您的主键(US1)就不会与同一个表中的“外键”(US2)相关。然后,您可以通过查询而不是大量循环来完成您尝试执行的操作。

不幸的是,我仍然不知道你到底想要完成什么,所以我不可能用你给出的内容创建一个示例场景。

于 2012-10-11T12:54:53.907 回答