How to write this kind of a query in mysql? - php

I have a table like this
a_count b_count total_count(a_count+b_count)
2 3
5 1
4 7
5 0
This is my table I need to update total count field using a single query. How can I write that kind of a query?
I need output like this
a_count b_count total_count(a_count+b_count)
2 3 5
5 1 6
4 7 11
5 0 5

To update the values of those fields in the table:
UPDATE mytable SET total_count = a_count + b_count
To get those fields from the table:
SELECT a_count, b_count, total_count FROM mytable
To get those fields without that total_count column:
SELECT a_count, b_count, (a_count+b_count) AS total_count FROM mytable

You can also write a trigger for that
DELIMITER //
CREATE TRIGGER `total_count` BEFORE INSERT OR UPDATE on `table`
FOR EACH ROW BEGIN
SET NEW.total = NEW.a+NEW.b;
END;
//
DELIMITER ;

Related

Update 2nd duplicate value in mysql table?

i have 52k rows of records in my user table. In that table user_hash column having approximately 2000 duplicate values. i want to update user_hash columns 2nd duplicate value. The following table user_id (3, 10), (5, 14) having same value and i want to update user_id 10 and 14 values. how can i update it with MySQL Qry?
--------------------------------
user_id user_hash user_status
--------------------------------
1 ae57250b 1
2 310cb4e0 1
3 28b365c7 1
4 0073265b 1
5 8bec42a9 1
6 00a5c443 1
7 e1c27b19 1
8 993dc301 1
9 8fc8a6bf 1
10 28b365c7 1
11 194714c0 1
12 4611d83a 1
13 277a426b 1
14 8bec42a9 1
15 740c1412 1
... ... ...
... ... ...
... ... ...
The following qry which i have used to check duplicate entry
SELECT user_hash, COUNT(user_hash)
FROM user_data
GROUP BY user_hash
HAVING COUNT(user_hash) > 1;
The first thing that comes to mind is that you may want to define a constraint such that in the future you can't have non-unique values where you don't want them.
The second thing is to ensure that these hashes can't legitimately collide/overlap.
Those thoughts aside (as they may be irrelevant to your use case):
update user_data set user_data.user_hash = STORED_PROC_FOR_HASH()
from (
select *, row_number() over(partition by user_hash order by (select null)) row_num
from user_data
) user_data
where row_num > 1
Source for the above query: https://stackoverflow.com/a/25090251/3080207
As hinted at by Nick, you'll need to be able to generate a unique hash, which is pretty much the 2nd component to this problem.
Hopefully that is helpful.

how to select multiple key value from one table with one query?

this is sample product properties table
product_id property_id property_value
5 1 white
5 2 50
5 3 50
5 4 55
5 5 mm
6 8 cm
i want filter my products dynamically. for example:
select property_id 1 and property_value white
AND
select property_id 2 and property_value 50
AND
select property_id 4 and property_value 55
AND
etc ...
i can make dynamic query from a basic query. when i use all conditions together, no record matched because all conditions operator is AND. what is the best query?
thanks for your answers.
It sounds like you're using the wrong keyword. Use OR instead of AND between the sets of criteria:
SELECT DISTINCT product_id
FROM product_properties
WHERE
(property_id = 1 and property_value = 'white')
OR
(property_id = 2 and property_value = '50')
OR
(property_id = 4 and property_value = '55')
OR
etc ...
You can use DISTINCT if you just want one of each product_id that matches the various criteria, or leave it off to get one for each row that matches.
Heading ##The basic query is:
SELECT
a.`*`,b.`*`
FROM
properties AS a
JOIN
properties AS b
ON
a.`product_id` = b.`product_id`
WHERE
a.`property_id` = '1' AND a.`property_value` = 'white'
AND
b.`property_id` = '2' AND b.`property_value` = '50'
Thanks to #mikhail-vladimirov https://stackoverflow.com/a/15208055/5129662

MySQL - Update Column if all rows are equal

I have N Rows with same SlNo but different RowNo as shown below
for eg:
SlNo RowNo Status
1 1 Opened
1 2 Closed
1 3 Opened
1 4 Closed
1 5 Opened
If all the Status Column Rows are Closed , I want to return 1.
else o.
Thanks in advance.
You can do it following:
SELECT STATUS FROM `table_1` where SLNO = 1 group by status
If you get only one record with value "Closed" then execute the next query
UPDATE `table_2` SET Ref_Status = 'Closed' WHERE SLNO = 1;
Update my_table set Status='Closed' where SlNo = 1
Find the count of all rows and check it with the count of Closed values.
Query
select t.`SlNo`,
case when t.`RowNo_Count` = t.`closed_count` then 1 else 0 end as `new_col`
from(
select `SlNo`,
count(`RowNo`) as `RowNo_Count`,
sum(case `Status` when 'Closed' then 1 else 0 end) as `closed_count`
from `your_table_name`
group by `SlNo`
)t;

MySQL: select last (max) value from column and count of all rows

How can I select last (=max) value from column and count of all rows in single query?
ID ITEM_ID VALUE
1 1 100
2 1 101
3 2 201
4 3 333
5 2 222
6 1 111
I want to select last / max value for particular ITEM_ID and count of all rows with this ID.
For ITEM_ID = 1 thus:
VALUE COUNT
111 3
My query is like this:
SELECT (SELECT COUNT(*) FROM table) AS count, (SELECT value FROM table ORDER BY id DESC LIMIT 1) AS value FROM table WHERE item_id = 1 LIMIT 1
It works but looks ... weird. Is there any better (simpler / faster) solution? Thanks
You need to do a GROUP BY on column ITEM_ID while getting the MAX() and COUNT() like
select max(value) as `VALUE`,
count(*) as `COUNT`
from your_table
group by ITEM_ID;

trying to delete duplicate records in sql but the query is going in an infinite loop

this is my table test
id identifier
--- ---------
1 zz
1 zzz
3 d
5 w
7 v
8 q
9 cc
9 ccc
here I want to remove the duplicate id's and keep the latest id's.
the identifier can have duplicate values it dose not matter but the id's should be unique.
I wrote this query to solve this problem but the problem is that it goes into a infinite loop.
please help me with this as I am not able to see the error.
Thanks
delete test
from test
inner join(
select max(id) as lastId, identifier
from test
where id in (
select id
from test
group by id
having count(*) > 1
)
group by id
)dup on dup.id = test.id
where test.id<dup.id
If you have an index on test(id, identifier), the following should be pretty efficient:
delete from test
where test.identifer < (select maxid
from (select max(identifier) as maxid from test t2 where t2.id = t.id
) a
)
The double nested query is a MySQL trick for referencing the update/delete table in the same query.
Look at How to delete duplicate rows with SQL?
And try this one(works for you want to do), i did with the identifier column, but with the date column as shown in the post is better.
DELETE FROM Test WHERE Identifier NOT IN
(SELECT MAX(Identifier) FROM Test GROUP BY Id);
Now with the DateField:
id identifier DateField
--- --------- ----------
1 zz 2013-02-01
1 zzz 2013-03-02
3 d 2013-03-02
5 w 2013-03-02
7 v 2013-03-02
8 q 2013-03-02
9 cc 2013-01-15
9 ccc 2013-03-02
that is the table, and row (1, zzz) is newer than (1,zz), you can know it by the DateField column, then this query deletes two rows (1, zz) and (9, cc) the oldest for Id's 1 and 9.
DELETE FROM Test WHERE Datefield NOT IN
(SELECT MAX(Datefield) FROM Test GROUP BY Id);
in SQL Server 2008 R2 i didnt get any error.
CREATE TEMPORARY TABLE tmp_tb_name AS
SELECT id,SUBSTRING_INDEX(GROUP_CONCAT(identifier ORDER BY id DESC),',',1)
FROM tb_name GROUP BY id ORDER BY NULL;
TRUNCATE TABLE tb_name;
INSERT INTO tb_name SELECT tmp_tb_name;
DROP TEMPORARY TABLE IF EXISTS tmp_tb_name;
Update
I have found a solution for the issue: This is how I did it to solve the issue
This is the solution which worked for me when there are millions on entities in the table.
Any other SQL query is creating a lot of processes and burdening the server.
$i=0;
while($i<10)
{
$statement="SELECT *
FROM test
WHERE id = :i";
$query=$db->prepare($statement);
$query->bindParam(':i',$i,PDO::PARAM_INT);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_ASSOC);
$c=count($results);
$temp=$results[$c-1];
$statement="DELETE FROM test WHERE id= :i";
$query=$db->prepare($statement);
$query->bindParam(':i',$i,PDO::PARAM_INT);
$query->execute();
$statement="Insert into test values(:id,:identifier)";
$query=$db->prepare($statement);
$query->bindParam(':id',$temp['id'],PDO::PARAM_INT);
$query->bindParam(':identifier',$temp['identifier'],PDO::PARAM_STR);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_ASSOC);
$i++;
}

Categories