How to update a column based on comparison result on another column - mysql

I can easily locate the rows I want with these sql statements:
SELECT COUNT(*) FROM `individuals` WHERE `company_zip` != '';
SELECT COUNT( * ) FROM `individuals` WHERE length( `company_zip` ) > 0;
SELECT COUNT( * ) FROM `individuals` WHERE strcmp( `company_zip`, '' ) != 0;
And there are probably 100 other ways to do this.
However...
Try using these in an UPDATE statement
UPDATE `individuals` SET `company_country` = 1 WHERE `company_zip` != '';
UPDATE `individuals` SET `company_country` = 1 WHERE length( `company_zip` ) > 0;
UPDATE `individuals` SET `company_country` = 1 WHERE strcmp( `company_zip`, '' ) != 0;
And I get responses like this:
0 row(s) affected. ( Query took 0.5920 sec )
I admit I am tired from looking at manual pages and google searches to figure this out. Which mysql principle am I missing here? It is easy to count the lines in SELECT statement but same criteria does not work for UPDATE statement. Is this a bug?
Darn! I figured it out just before posting. So I will give anyone wondering the answer.
I accidentally added field company_country with default value of 1 and so all records got default value of '1'. So mysql was trying to update fields, but found that they already were set to 1. Blanking them out allowed UPDATE queries to work. Nevermind. Posting for anyone who makes similar error.
Bradley

OK. To be specific, because all records already had field 'company_country' set to 1, mysql was telling me in a terse way, that it had not UPDATEd or changed any of the records. They started out with that field set to 1, and ended up with that field set to 1. Check your defaults people, especially is someone else set up the table. I could have typed
UPDATE `individuals` SET `company_country` = 1;
and the answer would still have been the same. 0 row(s) affected.

Related

Conditionally update column from another column in same table

I've looked through SO, and there are similar questions, but I can't seem to figure out how to do what I need.
For the purposes of this question, my table has 3 columns: reconciled (tinyint), datereconciled (timestamp, CAN BE NULL), and dateadded (timestamp).
For my code logic, if reconciled==1, there should be a timestamp in datereconciled, but I recently noticed that wasn't always happening. Fixed the code, but now have a lot of NULL values in datereconciled where there should be a timestamp. So, for all rows where reconciled==1 AND datereconciled==NULL, I would like to "update" the value FROM dateadded INTO datereconciled. If there is already a timestamp in datereconciled, leave it alone. And leave it alone if reconciled==0.
You should be able to use a simple update:
UPDATE YourTable
SET DateReconciled = DateAdded
WHERE DateReconciled IS NULL
AND reconciled = 1;
You basically wrote the query already
UPDATE table SET datereconciled = dateadded
WHERE reconciled = 1
AND datereconciled IS NULL
I figured I'd have to use a select in my update query, so I'm a victim of over-complicating things! However, here is my overly complicated self-discovered answer prior to the answers provided:
UPDATE
`transactions` AS `dest`,
(
SELECT
*
FROM
`transactions`
WHERE
`reconciled` = 1 AND `datereconciled` IS NULL
) AS `src`
SET
`dest`.`datereconciled` = `src`.`dateadded`
;

How to UPDATE with SELECT COUNT(), but only when count exists avoiding setting all rows to 0

So I tried to ask this question already, which was set to duplicate, wasting my time basically as it had nothing to do with the duplicate-question.
How to get rid of the php wrapping on this sql query
I have gotten so far, that I can affect the rows, that have new views. Sadly however, all other's will go to 0.
UPDATE `posts` SET `views_count` = views_count + (SELECT COUNT(*) AS `views` FROM `posts__views` WHERE `post_id` = `posts`.`id` GROUP BY `post_id`);
So I think, I need some WHERE, inside the first UPDATE to avoid affecting the rows, with 0 views.
After the UPDATE call, the posts__views table gets truncated. Otherwise the above would work.
EDIT: My objective is to update the posts table views_count, counting and grouping up the single views from posts__views table. After the main SQL process, the posts__views gets truncated and new views will be generated.
Originally the code was in PHP like so:
<?
# find new views grouped together:
$find_views = db::query("SELECT `post_id`, COUNT(*) AS `post_views` FROM `posts__views` WHERE `date_imported` IS NULL GROUP BY `post_id`;");
while ($view = db::fetch($find_views)) {
# Update the main production tables views_count column:
db::query("UPDATE `posts` SET `views_count` = views_count + {$view['post_views']} WHERE `id` = '{$view['post_id']}';");
# Update the post's views table... but why does it actually needs this update hmm..
db::query("UPDATE `posts__views` SET `date_imported` = NOW() WHERE `date_imported` IS NULL AND `post_id` = '{$view['post_id']}';");
}
# Trunkate post's views:
db::query("TRUNCATE TABLE `posts__views`;");

Mysql, delete several rows each N rows

I explain the problem, and the solution I tried to implement. I have a table with a lot of data, and I want to delete 4 rows each 5 rows. The aim is to have a lighter table.
This is my request :
SET #var_name = -1;
DELETE FROM myTable
WHERE id IN
(
SELECT id FROM myTable HAVING (#var_name := #var_name +1) % 5 !=0
)
The SELECT operation works properly, but together with the DELETE operation I get this message
#1093 - Table 'myTable' is specified twice, both as a target for 'DELETE' and as a separate source for data
I understand the meaning : I can't delete the table as it in the request. A workaround is possible : get the full list in a console, and execute the DELETE operation. It's better to perform it in one line.
Thanks for you help.
Thanks a lot
Do you try this one?
SET #var_name = -1;
DELETE FROM myTable WHERE (#var_name := #var_name +1) % 5 = 0

Update first row in SQL using LIMIT

I'm having a trouble with something that looks like simple thing. I'm trying to find first row that satisfies WHERE part of query and UPDATE it.
UPDATE Donation SET Available=0 WHERE Available != 0 and BloodGroup='" + bloodGroup + "' LIMIT 1"
bloodGroup is variable that gets filled automatically using C# and it keeps string value of selected blood group.
When I try to run this I get incorrect syntax near 'limit'.
What I'm doing wrong? Is it possible using LIMIT like during UPDATE query?
During debugging I got query like this:
UPDATE Donation SET Available=0 WHERE Available != 0 AND BloodGroup='AB-' LIMIT 1
Because C# is often used with SQL Server, perhaps the question is mistagged. The syntax looks fine for MySQL.
In SQL Server, you can do this as:
UPDATE TOP (1) Donation
SET Available = 0
WHERE Available <> 0 AND BloodGroup = 'AB-';
Note that this chooses an arbitrary matching row, as does your original query (there is no order by).
It is not safe to use limit in update queries.
Please refer
http://bugs.mysql.com/bug.php?id=42415
The documentation states that any UPDATE statement with LIMIT clause is considered unsafe since the order of the rows affected is not defined: http://dev.mysql.com/doc/refman/5.1/en/replication-features-limit.html
However, if "ORDER BY PK" is used, the order of rows is defined and such a statement could be logged in statement format without any warning.
You can use like this way limit in Update Queries like these
UPDATE messages SET test_read=1
WHERE id IN (
SELECT id FROM (
SELECT id FROM messages
ORDER BY date_added DESC
LIMIT 5, 5
) tmp
);
Also please
Can you try it? way of getting row_number
UPDATE Donation d1 join (SELECT id,(SELECT #Row:=0) as row,(#Row := #Row + 1) AS row_number FROM Donation where Available <> 0 AND BloodGroup='AB-') d2
ON d1.id=d2.id
SET d1.Available='three'
WHERE d1.Available <> 0 AND d1.BloodGroup='AB-' AND d2.row_number='1'

SELECT * FROM WHERE does not find all records

When I type:
select * from 'saleslog' where 'Status' = 'Pending';
or
select * from 'saleslog' where 'Status' = "Pending";
or
select * from saleslog where Status = 'Pending';
despite the fact that there are hundreds of rows with "Pending" value in Status column I get only 3 records displayed. The same happens when I look for value other than "Pending".
If however, I type:
select * from saleslog where status like "%Pending%";
then most if not all records are displayed. There are absolutely no spaces or any other characters in front and behind Pending value.
I am wondering if table "saleslog" needs to be repaired and if so, how? I'm kind of new to SQL.
It's possible there are hidden characters in the field that you just can't see such as tab, carriage return or line feed. Have you tried doing an update on the field to try and correct it? Maybe try running the update query below and then run your SELECT query again:
UPDATE saleslog SET status = 'Pending' WHERE status LIKE '%Pending%'
Try the following:
UPDATE `saleslog` SET `status` = TRIM(`status`);
SELECT * FROM `saleslog` WHERE `status` = 'Pending';