473,394 Members | 1,821 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

INSERT into one table based on data from another table

Hi, I am trying to do something in SQL that I have done in PHP, but I am trying to have the operation performed as a stored procedure because of the sheer number of inserts I have to perform in PHP. I could really use some help!

I'm not how to assign variables based on subqueries, or how to even structure the nested queries...

I have a table with the following fields

scores
userId INT
testId INT
score INT

and I would like to correlate all of the users in another table 'correlations',

correlations
user1 (FK scores)
user2 (FK scores)
total_delta (the total of the difference in test scores between user1 and user2)
num_common_tests (number of tests both users have taken in common)
avg_delta (total_delta/num_common_tests)

in PHP i'm doing the following:
[PHP]
/**
* Loads all test scores into an array from the database, ordered by userId
* Array has the form [userId,[index,testId,score]]
* ...this takes very little time
*/
function get_user_scores(){
global $user_scores,$users,$num_users,$con,$table,$query_ limit;

$sql = "select userId, testId, score from ".$table." order by userId limit ".$query_limit;
$rs = mysql_query($sql) or die(mysql_error()."<br>".$sql); //pointer to resultset from database

while ($row = mysql_fetch_assoc($rs)) {
$testId= intval($row['testId']);
$score= intval($row['score']);
$userId = intval($row['userId']);
if(array_key_exists($userId,$user_scores)){
array_push($user_scores[$userId],array($testId,$score));
} else {
$user_ratings[$userId] = array();
array_push($user_scores[$userId],array($testId,$score));
}
}
$users = array_keys($user_scores);
$num_users = count($users);

}

/**
* Builds the correlation array. For each user, compares other users who have at least one shared test.
* This builds an N choose 2 array with the form [index,user1,user2,cummulative delta,num common tests,avg delta]
* ...very slow when users > 100
*/
function build_correlations(){
global $num_users,$users,$correlation_array,$correlation_ array_index;
for ($i=0; $i < $num_users; $i++){
$user1 = $users[$i];
for ($k = $i+1; $k < $num_users; $k++){
$user2 = $users[$k];
$user1_correlation = correlate_users($user1,$user2);
if($user1_correlation!=null){
$correlation_array[$correlation_array_index] = $user1_correlation;
$correlation_array_index++;
}
}
}
}





/**
* Calculates the correlation between 2 users
*/
function correlate_users($user1,$user2){
global $correlation_array,$user_scores;
$user1_scores= $user_scores[$user1];
$user2_scores= $user_scores[$user2];
$total_delta = 0;
$num_common_tests = 0;
foreach ($user1_scores as &$value1){
$test1 = $value1[0];
$user1_score = $value1[1];
foreach ($user2_scores as &$value2){
$test2 = $value2[0];
if ($test1 == $test2){ //shared test, we can calculate a correlation
$user2_score = $value2[1];
$delta = abs($user2_score - $user1_score);
$total_delta += $delta;
$num_common_tests++;
}
}
unset($value2);
}
unset($value1);

if($num_common_tests > 0){ //add to correlations array
$avg_delta = $total_delta/$num_common_tests;
return array($user1,$user2,$total_delta,$num_common_tests ,$avg_delta);
}
return null;
}

/**
* Saves contents of correlation array to the database
*/
function save_correlations(){
global $con,$correlation_array;

for($i=0; $i < count($correlation_array); $i++){
$sql = "insert into correlations (user1, user2, total_delta, num_common_tests, avg_delta) values (". $correlation_array[$i][0] .",". $correlation_array[$i][1] .",". $correlation_array[$i][2] .",". $correlation_array[$i][3] .",". $correlation_array[$i][4] .")";
$rs = mysql_query($sql) or die(mysql_error()."<br>".$sql);
}

print("Correlations saved<br>\n");

}
[/PHP]
Oct 27 '07 #1
0 3801

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: traceable1 | last post by:
I am inserting data rows into a table via a stored procedure. After the inserts, I query the rows in the table and I want them to spit back out in the same order I put them in. However,...
1
by: shottarum | last post by:
I currently have 2 tables as follows: CREATE TABLE . ( mhan8 int, mhac02 varchar(5), mhmot varchar(5), mhupmj int )
16
by: Philip Boonzaaier | last post by:
I want to be able to generate SQL statements that will go through a list of data, effectively row by row, enquire on the database if this exists in the selected table- If it exists, then the colums...
16
by: robert | last post by:
been ruminating on the question (mostly in a 390/v7 context) of whether, and if so when, a row update becomes an insert/delete. i assume that there is a threshold on the number of columns of the...
3
by: Nicolae Fieraru | last post by:
Hi All, I have a problem and I can't figure out how to solve it. My database has three tables: tblCustomers, with CustomerId and CustomerName tblProducts, with ProductId and ProductCode...
8
by: Carl | last post by:
Hi, I hope someone can share some of their professional advice and help me out with my embarissing problem concerning an Access INSERT query. I have never attempted to create a table with...
10
by: Mike | last post by:
I know this sounds strange but I am at a loss. I am calling a simple funtion that opens a connection to a SQL Server 2000 database and executes an Insert Statement. private void...
6
by: rn5a | last post by:
During registration, users are supposed to enter the following details: First Name, Last Name, EMail, UserName, Password, Confirm Password, Address, City, State, Country, Zip & Phone Number. I am...
0
by: mwenz | last post by:
I am trying to update an Access table using OLEDB in VB.Net 2005. I can add rows but I cannot update them. Code to instantiate the Access database and table... Dim conn As New...
4
by: =?Utf-8?B?RXJpYyBGYWxza2Vu?= | last post by:
We’re storing our main entity in an insert only table which stores the history of past revisions, but we’re facing problems with storing this history as LINQ will only update the entity, and...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.