When i try to combine 3 tables having 50K records and write a MySQL select query:
select t1.c1,t2.c2 from table1 t1,table2 t2,table3 t3
where t3.column3='<value>' and t1.column1=t2.column1
and t2.column2=t3.column2
and t2.column2='<value1>' or t2.column2='<value2>'
This is the kind of the query which am writing to run
I get "mysql client ran out of memory"
Any help on how to overcome this will be highly appreciated.
Thanks
What client do you use? For mysql you can try running it with --quick option
Here's what I wrote to get around the memory limit. You'll have to modify the limits to match your environment. I'm breaking my results into a 500 per record batch and processing that and then looping into the next $records_per_batch.
<?php
// variables
$counter = 0;
$records_per_batch = 500;
$total_records = 0;
$app_root = "/var/run/consumers";
// mark the start time
system("/bin/touch $app_root/clean.last_start");
$link = mysqli_connect("localhost", "username", "password", "database") or die(mysqli_error());
// get the total amount of records to process
$sql = "SELECT COUNT(*) from table";
$result = mysqli_query($link, $sql) or die("couldn't execute sql: $sql" . mysql_error());
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$total_records = $row[0];
}
// iterate through the records at $records_per_batch at a time
$sql_template = "SELECT * FROM table order by table_id limit %s, %s";
while ($counter < $total_records) {
$sql = sprintf($sql_template,$counter,$records_per_batch);
$result = mysqli_query($link, $sql) or die("couldn't execute sql: $sql" . mysql_error());
if ($result) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
// do your work here.
}
}
} else {
print "hmm, no result\n";
exit;
}
$counter += $records_per_batch;
}
mysqli_close($link);
system("/bin/touch $app_root/clean.last_end");
?>
I know this post is old but I think it's worth mentioning that the or is probably causing an issue as well.
Here it is with some joins, and specifying the or for the t2 value only, which is what I think you want. This should limit your result set.
select t1.c1,t2.c2
from table1 t1
inner join table2 t2 on t2.column1=t1.column1
inner join table3 t3 pm t2.column2=t3.column2
where t3.column3='<value>'
and t2.column2 IN('<value1>','<value2>');
50K records is not too large to give you the type of problem described. You can try optimizing your tables by indexing on columns that join or limit such as t2.column1, t2.column2, etc.
Related
I have a couple of MySQL tables where I run a query on like this:
$sql = "
SELECT my_item
FROM t1
, t2
WHERE t1.id='$id'
AND t2.spec IN (208, 606, 645)
AND t1.spec = t2.spec
";
Note I am using the WHERE IN.
Next I run a query and use WHILE to try to get the results:
$retval = mysql_query($sql) or die('Query failed: ' . mysql_error());
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$myitem = $row['my_item'];
echo "My item is $myitem<br />\n";
}
This prints three results, each with a different value for $myitem, based on the three options from the IN clause in the SELECT statement at the beginning.
How can I extract and store each of these three values in a separate variable each?
Thank you!
use join
SELECT my_item FROM t1 join t2
on t1.spec=t2.spec
WHERE t1.id='$id'
AND t2.spec IN (208, 606, 645)
or create array
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$myitem[] = $row['my_item'];
}
use this array likt that :-
foreach( $myitem as $myitems){
echo "My item is $myitems<br />\n";
}
or use indexing
echo "My item is $myitems[0]";
You can store the $row['my_item'] in an array.
Refer PHP arrays
I'm trying to sum my MySQL column value with number, here is my php script, i dont think im doing in right way. I was searching in stackoweflow but i havent found how to sum with specific number, not with other column.
<?php
$currentUser = isset($_POST['currentUser']) ? $_POST['currentUser'] : '';
$currentTasken = isset($_POST['currentTasken']) ? $_POST['currentTasken'] : '';
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
if(!$con)
die('Could not connectzzz: ' . mysql_error());
mysql_select_db("foxi" , $con) or die ("could not load the database" . mysql_error());
$check = mysql_query("SELECT * FROM dotp_task_log");
$numrows = mysql_num_rows($check);
if($numrows >= 1)
{
//$pass = md5($pass);
$ins = mysql_query("INSERT INTO dotp_task_log (task_log_creator, task_log_Task) VALUES ('$currentUser' , '$currentTasken')" ) ;
if($ins)
$check = mysql_query("SELECT * FROM dotp_task WHERE task_id='$currentTasken'");
$numrows = mysql_num_rows($check);
if($numrows == 1)
{
//$pass = md5($pass);
$ins = mysql_query("SELECT (SELECT SUM(task_percent_complete) FROM dotp_task WHERE task_id='$currentTasken') FirstSum, (SELECT SUM(5)), SecondSum ");
if($ins)
die("Succesfully summed!");
else
die("ERROR");
}
else
{
die("Cant sum!");
}
die("Succesfully Created Log!");
else
die("ERROR");
}
else
{
die("Log already exists!");
}
?>
Your query is not written properly. Try to run this query from MySQL command line or from PHPMyAdmin. It will give you an idea what the error is. My best guess is that the first part of the query is not complete.
This is what it will resolve to
SELECT n FirstSum, 5, SecondSum
Where n is the value returned from the subquery. This is a syntax error. Try to remove the last comma before SecondSum.
This is what your query should be:
SELECT (SELECT Sum(task_percent_complete)
FROM dotp_task
WHERE task_id = '$currentTasken') FirstSum,
(SELECT Sum(5)) SecondSum
remove
(select sum(5))
and replace it with
(select 5)
I am very confused about this (returning false):
$sql = "SELECT * from tbl_user WHERE group = 'abc'";
$res = mysql_query($sql);
if(mysql_num_rows($res) > 0) {
$response = array('status' => '1');
} else {
$response = array('status' => '0'); // ---> what I get back
die("Query failed");
}
...despite the fact the field group is present in mySQL database. Even more strange is that the following return the value of group:
$SQL = "SELECT * FROM tbl_user";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['group']; // ---> returns 'abc'
When I execute a WHERE clause with every other fields of my table excepting group (for example WHERE name = 'ex1' AND ID=1 AND isAllowed=0 (and so on...), everything is fine. As soon as I insert group = 'abc', I get nothing...
This makes me mad. If anyone could help... (I am running a local server with MAMP).
Thanks a lot!
The issue is that group is a reserved word in SQL.
For MySql you need to escape it with backticks
`group`
So your query would be
$sql = "SELECT * from tbl_user WHERE `group` = 'abc'";
If I want to select whether i am following the threads or not.
I have two approaches to do so... but I don't know which one would be more better in terms of performance and speed. Can anyone help me out?
Approach 1
$cui = $_SESSION['user_id'];
$data = mysqli_query($con,"
SELECT t.*,( select count(follow_id) from follows where object_id =
t.thread_id AND object_type='thread' AND user_id = $cui) as me_follow FROM threads t
");
while($row = mysqli_fetch_assoc($data)){
/*
$row['me_follow'] = 0 if i aint following
$row['me_follow'] = 1 if i am following
*/
}
Approach 2
$cui = $_SESSION['user_id'];
$data = mysqli_query($con,"SELECT * FROM threads");
$ids = array();
while($row = mysqli_fetch_assoc($data)){
$ids[] = $row['thread_id'];
}
$ids = join($ids,",");
$data = mysqli_query($con,"SELECT COUNT(*) FROM follows WHERE object_id IN($ids) AND user_id = $cui");
One round-trip wins over two. This is because there is some overhead in sending SQL to the server, having it parse it, execute it and send the results back. It is (usually) better to do everything in one round-trip.
I need to connect to a MySQL database and then show the number of rows. This is what I've got so far;
<?php
include "connect.php";
db_connect();
$result = mysql_query("SELECT * FROM hacker");
$num_rows = mysql_num_rows($result);
echo $num_rows;
?>
When I use that code I end up with this error;
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\Documents and Settings\username\Desktop\xammp\htdocs\news2\results.php on line 10
Thanks in advance :D
You would probably be better of asking the database to aggregate the number of rows instead of transferring them all to php and doing the counting there.
SELECT COUNT(*) FROM hacker
take a habit to run all queries this way:
$sql = "SELECT * FROM hacker";
$res = mysql_query($query) or trigger_error(mysql_error().$sql);
and you will always have comprehensive error information
and take appropriate corrections
also, as it was mentioned above, the only reliable way to count rows is SELECT count(*) query
$sql = "SELECT count(*) FROM hacker";
$res = mysql_query($query) or trigger_error(mysql_error().$sql);
$row = mysql_fetch_row($res);
$count = $row[0];
change your code as following:
$result = mysql_query("SELECT * FROM hacker");
echo mysql_error();
You have an SQL-Error or your not connected to the database