1

Having trouble to create quality and optimize mysql query. Lets create a table with values.

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');

What i am trying to achieve:

$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 = returns 4 values ( tere1, tere2, tere3, tere4 ). I whant the script to count for each of these values, the number of entries from US1. $second = returns 2 values ( tere5, tere6 ). Count value would be (2) on first php while loop. How to create a good mysql script so that this will work and if there would be a lot of users accsesing this page, the server wont crash and speed of the query would be much less.

Thank you

I am traying to achieve a pyramid scheme. Where 'rasim' is the primary user name. Where $second , $third and $four is a int number of users per level. $second will have caount of all users in the second level of the pyramid.

Example image how it will look like. http://silverstream.ee/img/stack.PNG

4

2 に答える 2

0

ここでの最良の選択肢は、データを別々のテーブルに分割して、主キー (US1) が同じテーブル内の「外部キー」(US2) と関連しないようにすることだと思います。その後、多数のループとは対照的に、クエリでやろうとしていることを達成できます。

残念ながら、あなたが何を達成しようとしているのかわからないので、あなたが与えたものを使ってシナリオ例を作成することは不可能です.

于 2012-10-11T12:54:53.907 に答える
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 に答える