Delete rows in MySQL database table based on column parameter - php

I have JSON data continuously inserted into a DB table but there are some rows which I need to delete concurrently based on the column value. For eg., I need to delete the rows which have a column value (time_min) of more than 90 minutes.
ID time_min
1 50
2 30
3 91
4 40
5 93
6 95
7 40
Here I need to delete rows containing values more than 90 in time_min column.
This is the current code I'm using.
if($time_min >= 91){
$sql = "truncate table_name";
if ($conn->query($sql) === TRUE) {
echo "Rows Dropped";
}
}
It clearly is deleting the entire table values which mess up in the loading of new values.
I would just want the rows that have column value of more than 90 in time_min (column name) to be deleted.
Would appreciate if someone can guide me on this.

You could use a where condition for check the 90 time_min for delete
delete from my_table
where time_min > 90

try this-
DELETE FROM `table_name` where table_name.time_min>90

Use WHERE Clause condition on column in the query
DELETE FROM 'table_name' tbn WHERE tbn.time_min>90

Related

Sql – Insert value in first empty cell of column and show ID

I have a SQL statement that will insert a value into the first empty cell. If I run the PHP script again then it inserts into the next null cell etc.
Problem: I also want to find out the ID of that row, and the value of another column in that row. In the MySQL table below, I want a value inserted in the first ‘null’ of COLUMN A, and also know the ID and value in COLUMN B corresponding to that (i.e. ID= 3 and COLUMN B= 11).
My_TABLE
ID COLUMN A COLUMN B
1 6 78
2 7 90
3 NULL 11
4 NULL 5
5 NULL 123
The following sql statement in PHP script will make it possible to insert value to the first empty cell in COLUMN A:
UPDATE My_TABLE
SET COLUMN A = 83
WHERE COLUMN A IS NULL
LIMIT 1;
Result will be:
ID COLUMN A COLUMN B
1 6 78
2 7 90
3 83 11
4 NULL 5
5 NULL 123
I also want to have an SQL script that will print within PHP (echo) the corresponding values of the ID and COLUMN B of the last updated COLUMN A null value (i.e. ID= 3; COLUMN B= 11).
How do I do that?
Here you go
<?php
// just in case, for comparison
$q = 'SELECT `id`,`colB` FROM My_TABLE WHERE `colA` IS NULL ORDER_BY `id` LIMIT 1';
$row = $pdo->query($q)->fetch(PDO::FETCH_ASSOC);
if ($row) {
// voialà, the value for COLUMN B is now known
list($id, $colB) = $row;
$q = 'UPDATE My_TABLE SET `colA`=? WHERE `id`=?';
$stmt = $pdo->prepare($q);
// voilà, your row is updated
$stmt->execute(array($valueForColumnA,$id));
}
Beware, do not copy and paste whis nilly-willy. Read it, look at it, smell it and understand it. Any questions?

inserting values to new table in mysql_query

Okay guys, I will try to share my guestion understandable. So I have 2 tables like below:
ALL Id from TABLES are Autoincrement.
Number
id number
10 100
11 102
12 105
13 106
subnumber
id number_id subnumber
52 10 10
53 11 15
54 13 40
You see some numbers (not all) have subnumbers. I mean:
From table number the number where id = 13 has subnumber and it is equal to 40.
I want to save this table in another table.
$sql1=mysql_query('SELECT number FROM number');
$while(fetch1=mysql_fetch_array($sql1))
{
mysql_query('
INSERT INTO `save_number` (number)'
VALUES ('.$fetch1['number'].');
);
}
save_number
id number
100 100
101 102
102 105
103 106
Now i gonna save table (subnumber) in another table (save_subnumber)
$sql2=mysql_query('SELECT number_id, subnumber FROM subnumber');
$while(fetch2=mysql_fetch_array($sql2))
{
mysql_query('
INSERT INTO `save_subnumber` (number_id, subnumber)'
VALUES ('.$fetch2['number_id'].', '.$fetch2['number'].');
);
}
save_subnumber
id number_id subnumber
60 10 10
61 11 15
62 13 40
So, you see the number_id FROM save_subnumber is not equal to new inserted id FROM save_number. I would be appreaciated if anyone help me. By the way I am still using mysql_query. I can not find time to improve my SQL to PDO :)
Your first query can be changed to
INSERT INTO
save_number (number)
SELECT
number
FROM
number
This will save you using PHP to iterate through rows and will be faster. A lot.
Having this in mind your second query would be
INSERT INTO
save_subnumber (number_id, subnumber)
SELECT DISTINCT
sn.id, s.subnumber
FROM
saved_number AS sn
CROSS JOIN
number AS n
USING (number)
INNER JOIN
subnumber AS s
ON
n.id = s.number_id
If you just want to copy one table in another why don't you use something like this
INSERT INTO save_number SELECT * FROM number;

Counting number of times a value occurs and sending count to another column?

I have a table that I have fed data into through a PHP script, and am managing it using phpMyAdmin. My table has 4 columns. The first is an auto increment, second and third are values being fed in, and the final is meant to keep track of how many times the value from column 3 has appeared.
This is how my table currently appears
RowNumber UserID SongID Plays
1 540 2191 0
2 540 2671 0
3 550 3891 0
4 550 2191 0
5 550 2671 0
6 560 9391 0
7 560 2191 0
I want to search through the whole table and change the value in the Plays column to show how many times the value appears in the table.
Ideally, this is how I want my table to output:
RowNumber UserID SongID Plays
1 540 2191 3
2 540 2671 2
3 550 3891 1
4 550 2191 3
5 550 2671 2
6 560 9391 1
7 560 2191 3
Is there a way to search through the table and update these values?
The amount of data being inputted into the table is quite large, so an efficient solution would be greatly appreciated.
Consider using a view instead of a table, unless you need the value cached for performance reasons. You can compute the count of each value in a subquery and join the results back to the table like so:
SELECT Table.RowNumber, Table.UserID, Table.SongID, x.Plays
FROM Table
INNER JOIN (
SELECT SongID, COUNT(*) AS Plays
FROM Table
GROUP BY SongID
) x
ON Table.SongID = x.SongID;
And create a view from it using CREATE VIEW TableWithPlays AS SELECT .... Having an index on SongID will allow the subquery to complete rather quickly, and you will never have to worry about the Plays column being up to date.
If you do in fact want to cache the values, use an UPDATE query based on the above query:
UPDATE Table a
INNER JOIN (
SELECT SongID, COUNT(*) AS Plays
FROM Table
GROUP BY SongID
) b
ON a.SongID = b.SongID
SET Plays = b.Plays;
As with the view solution, don't forget the index on SongID.
I think you can use simple PHP query that is run periodically (Note: not an actual code):
$sql = "SELECT UserID, SongID, COUNT(RowNumber) AS CNT FROM SomeTable GROUP BY 1, 2 ORDER BY 3 ASC";
foreach($result as $row){
$sql = "UPDATE SomeTable SET Plays = ".$row['CNT']." WHERE UserID = '" . $row['UserID'] . "' AND SongID = '" . $row['SongID'] . "'";
}

Mysql update a row with another row value in same table

I have a table. I want to update the 5th row with 10th row values from the same table. For example:
SlNo Name Quali Exp
1 x B.E 2
2 y BSC 3
3 Z B.A 1.5
4 A MSC 2
5 B MBA 5
Here i want to update second row with the value of 5th row.
Here is my current query:
UPDATE table
SET Name=(select Name from table where slNo='5'),
Quali=(select Quali from table where slNo='5'),
Exp=(select Exp from table where slNo='5')
where slNo='3';
this is working fine ... but if there are more than 20 columns it becomes laborious to write a query this way, because for each column I have to include another sub-query... is there any other way to write query to update the whole row with all values from the other row in the same table?
Use a self-join with the multiple table UPDATE syntax:
UPDATE `table` AS t1 JOIN `table` AS t2 ON t2.slNo = 5
SET t1.Name = t2.Name, t1.Quali = t2.Quali, t1.Exp = t2.Exp
WHERE t1.slNo = 3

PHP Mysql trying to pull multiple rows from different tables (works for 3 rows on 2 tables but not 4 rows from 3 tables)

I'm trying to pull multiple rows from different tables in a database.
If I only have the first 3 rows from two tables, it works fine. As soon as I add the third table and try and pull another row it breaks!
Ultimately what I'm trying to do is pull the image, the dayid, the name of a person, and then name of a cause.
The imageURL and the Outfitday_id are in the same table, the name of the person is in the table Pilot, and the name of the cause is in the table cause.
For some reason it will pull the first two rows (imageUrl, outfitDay_id) from the table Outfitimage, then pull the 3rd row (name) from Pilot, but fails if I add the name and try and pull it from the Cause table.
$link = mysql_connect("host","user","pass");
if ($link) {
mysql_selectdb("up",$link);
// Select records from the DB
$query = "SELECT imageUrl,outfitDay_id,name,name FROM OutfitImage,Pilot,Cause ORDER BY Rand(" . date("Ymd") . ") LIMIT 1";
$image = mysql_query($query);
// Display records from the table
echo "";
while ($row = mysql_fetch_array($image, MYSQL_NUM)) {
echo "<IMAGE SOURCE='$row[0]'/><br>";
echo "<div id='info'>Day $row[1] of ";
echo "$row[2] Uniform Project for$row[3] </div>";
}
echo "";
} else {
echo "Can't connect to the database!";
}
It probably happens because the name column is ambiguous. I'm guessing you have a name column in both the Cause and Pilot (or some other table). MySQL can't guess what table you want to retrieve the column value from, and will spit an error (Column name in field list is ambiguous).
Make sure you prefix the column name with the table name to remove ambiguity:
SELECT
imageUrl, outfitDay_id, Cause.name, Pilot.name
FROM
OutfitImage, Pilot, Cause
You are attempting a cross-join across all three tables, but you aren't creating any conditions to filter them out. The clause FROM table1, table2, table3 attempts a cross-join across all three tables. A cross-join means every row from one table is paired up with every row from another table. For example, say I have three tables, each have two rows. The first table I call names with the two rows jack and jill, the second table I will call ages with rows 21 and 24, the third table will be genders, and have rows male and female. If I do a clause FROM names, ages, genders, it will return a table with 2 X 2 X 2 = 8 rows.
names ages genders
jack 21 male
jack 21 female
jack 24 male
jack 24 female
jill 21 male
jill 21 female
jill 24 male
jill 24 female
Normally, when you cross-join, you also add a condition to WHERE to filter out rows that don't make sense. For example, from example FROM clause you might have a WHERE genders.id = names.genders_id. In this case, you are linking a name with a specific gender row from the genders table. This will probably also solve your need for a LIMIT 1.

Categories