how to select alternate rows from mysql using php - php

I want to select rows alternatively in mysql using php,
<?php
$result=mysql_query("select * from marker1 where date='$maxdate' and time BETWEEN '$mintime' AND '$maxtime' and imei_no='$vehicle_imei_no1'")or die(mysql_error());
?>
this is my query but it select all rows, in database i m not getting serialy data so i can't use this query
select t.id, name
from (select id, name, ROW_NUMBER() over (order by id) as srNo from Employee) t
where (t.srNo % 2) = 1
i only differentiate by time '11:05:30' in this formate
please guide me how to use query for alternative rows.
Thanks

Maybe this would work!:
select * from marker1 where date='$maxdate' and time BETWEEN '$mintime' AND '$maxtime' and imei_no='$vehicle_imei_no1'
AND (marker1.ID % 2) == 0
marker1.ID is the primary key and I'm supposing it as auto_increment.
This should select only the even values.

$sql = "SELECT * FROM Orders LIMIT 15, 10";
It would start from record 15th and return 10 records.
Ref: Link

Related

What PDO query should i use?

I have a table on my database which called topics(topic_id,topic_subject,topic_content,topic_date,topic_cat,topic_comm,topic_by,votes,tags,views,flags), from this table i want to echo
10 top users(topic_by) with the most topics(max number of topics) on a specific community(topic_comm). What PDO query should i use ? I think need something like below:
$sql = $conn -> prepare("SELECT topic_by WHERE topic_comm=:comm AND ( MAX COUNT(topic_id) )")
Let construct the query step by step. In order to get the top 10 user by most topic by community, you need to compute number of topic by each user on that community.
SELECT topic_by, COUNT(*) AS total_topic FROM topic
WHERE topic_comm = :comm GROUP BY topic_by
Then, you want to get the top 10 user, you can use basic subquery and LIMIT. So the final query
SELECT * FROM (
SELECT topic_by, COUNT(*) AS total_topic FROM topic
WHERE topic_comm = :comm GROUP BY topic_by
) AS t ORDER BY t.total_topic DESC LIMIT 10

Mysql query to select records where the sum of a column's values is in a given variable range

I've been trying to write a query to select all records from a table where the sum of a column's values is between a variable range.
Here's what I came up with so far:
$result = mysql_query(' SELECT * FROM table WHERE SUM(column) BETWEEN $Range1 AND $Range2 ORDER BY RAND());
However when I try to loop through the above query with the mysql_fetch_object function it gives me a common error (The supplied argument is not a valid result).I've tried different ways of writing it but still come up short
So I tried the query using aliases you guys provided but still get the same error.
$result = mysql_query(' SELECT column1, SUM(column2) AS Total FROM table GROUP BY column1 HAVING Total BETWEEN $Range1 AND $Range11 ORDER BY RAND()');
I'm not sure what the "ordering by rand" is needed for but your final query will look something like this:
SELECT *, SUM(column) AS `total`
FROM table
GROUP BY someColumn
HAVING `total` BETWEEN $Range1 AND $Range2
ORDER BY RAND()
;

Single mysqli query statement to get total number of rows and limit also

I want to fetch the total count of records in MySQL db table and also use the limit with this. For example, there are 100 rows and the limit I want to use let suppose is 10. I know how to do this using two queries but I want to do this in one go.
SELECT count(*) as total_rows FROM mytable; // gets the total count of rows
SELECT col1,col2 FROM mytable LIMIT 0, 10; // gets the 10 rows of col1,col2
I want to do this in one go. Any idea.
Thanks.
Here is the SQL Fiddle that demonstrates how the below works:
SELECT m.*,
(
SELECT COUNT(*)
FROM mytable AS sm
) AS TotalCount
FROM (
SELECT mt.col1, mt.col2
FROM mytable AS mt
LIMIT 0, 10
) AS m
Have a look at Shayan Husaini's answer on How to get the total row count with MySQLi
I have updated his original answer after trying it out myself. You have to add "SQL_CALC_FOUND_ROWS" after SELECT in your query and add a second query as shown in the code snippet below.
$sql1 = "SELECT SQL_CALC_FOUND_ROWS col1,col2 FROM mytable LIMIT 0, 10";
$sql2 = "SELECT FOUND_ROWS()";
$result1 = $conn->query($sql1);
$result2 = $conn->query($sql2);
$TotalRcount = $result2->fetch_row();
// I have added this next line to correct the answer
$TotalNumRows = $TotalRcount[0];
You can use $result1 to access your results as you normally would.

How to add a single column php/mysql

I'm trying to add a single column in a db query result. I've read about the SUM(col_name) as TOTAL, GROUP BY (col_name2).
But is there a way i can only SUM the column without any GROUPing? I a case whereby all col_name2 are all unique.
For example... I have a result with the following col headers:
course_code
course_title
course_unit
score
grade
Assuming this have 12 rows returned into an HTML table. Now i want to perform SUM() on all the values (12 rows) for the column course_unit, in other to implement a GPA school grading system.
How can i achieve this.
Thanks.
SELECT SUM(col_name) as 'total' FROM <table>
GROUP BY is required only if you want to sum subsets of the rows in the table.
You can find sum or any aggregate db functions (such as count, avg, etc) for most cases without using group clause. Your sql query may look something like this:
SELECT SUM(course_unit) as "Total" FROM <table_name>;
As comments below have already pointed out: SELECT SUM(course_unit) AS total FROM your_table;. Note that this is a separate query to the one with which you retrieve the table data.
This does it in php. I'm not sure how to do it with pure sql
$query = "SELECT * FROM table";
$result = mysql_query($query);
$sum = 0;
while($row = mysql_fetch_assoc($result))
{
$sum+= intval($row['course_unit']);
}
echo $sum;
SELECT
course_code,
course_title,
course_unit,
score, grade,
(select sum(course_unit) from TableA) total
from TableA;

Update values of database with values that are already in DB

I've a database that stores data read from different sensors. The table looks like this:
[SensorID][timestampMS][value]
[Sensor1][123420][10]
[Sensor1][123424][15]
[Sensor1][123428][6554]
[Sensor1][123429][20]
What I would like to do is the following: There are some reads that are corrupted (numbers that are 6554), and I would like to Update that with the next value that is not corrupted (in the example shown below that would be 20). So, if a number is 6554, I would like to update that with the next value (in timestamp), that is not corrupted.
I was thinking on doing this in PHP, but I wonder if it's possible to do it directly with a SQL script.
Appreciate :)
You can use a correlated sub-query...
UPDATE
myTable
SET
value = (SELECT value FROM myTable AS NextValue WHERE sensorID = myTable.SensorID AND timestampMS > myTable.timestampMS ORDER BY timestampMS ASC LIMIT 1)
WHERE
value = 6554
The sub-query gets all the following results, ordered by timestampMS and takes just the first one; That being the next value for that SensorID.
Note: If no "next" value exists, it will attempt to update with a value of NULL. To get around this, you can add this to the WHERE clause...
AND EXISTS (SELECT value FROM myTable AS NextValue WHERE sensorID = myTable.SensorID AND timestampMS > myTable.timestampMS ORDER BY timestampMS ASC LIMIT 1)
EDIT
Or, to be shorter, just use IFNULL(<sub_query>, value)...
Not sure if this is valid syntax, can't test it ATM. You may need to change this to be JOINs instead of the nested subqueries, but in concept you can do something like (for SQL Server):
UPDATE t1
SET Value = ( SELECT Value
from MyTable t2
WHERE t2.SensorID =t1.SensorID
AND t2.[timestamp] =
( SELECT MIN([TimeStamp])
FROM mytable t3
where t3.sensorid = t2.sensorID
AND t3.[timestamp] > t2.[timestamp]
)
)
FROM Mytable t1
WHERE t1.value = 6554
I did a workaround based on Dems solution, and it works in Mysql:
I've created a "copy" of the sensors table like this:
drop table if exists sensors_new;
create table if not exists sensors_new like sensors;
insert into sensors_new select * from sensors;
Then I do what Dems recommended me doing, but using this new aux table in the select (to avoid the error that Mysql launches when Updating a table while doing a select in the same table).
UPDATE
sensors
SET
raw_data = (SELECT raw_data FROM sensors_new AS NextValue WHERE sensor_id = sensors.sensor_id AND timestampMS > sensors.timestampMS ORDER BY timestampMS ASC LIMIT 1)
WHERE
value = 6554
Then, just drop this auxiliar table.
I hope this helps Mysql users.

Categories