I have a simple mysql table:
CREATE TABLE IF NOT EXISTS `pers` (
`persID` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(35) NOT NULL,
`gehalt` int(11) NOT NULL,
`chefID` int(11) DEFAULT NULL,
PRIMARY KEY (`persID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `pers` (`persID`, `name`, `gehalt`, `chefID`) VALUES
(1, 'blb', 1000, 3),
(2, 'as', 1000, 3),
(3, 'chef', 1040, NULL);
I tried to run following update, but I get only the error 1093:
UPDATE pers P
SET P.gehalt = P.gehalt * 1.05
WHERE (P.chefID IS NOT NULL
OR gehalt <
(SELECT (
SELECT MAX(gehalt * 1.05)
FROM pers MA
WHERE MA.chefID = MA.chefID)
AS _pers
))
I searched for the error and found from mysql following page http://dev.mysql.com/doc/refman/5.1/en/subquery-restrictions.html, but it doesn't help me.
What shall I do to correct the sql query?
It's quite simple. For example, instead of writing:
you should write
or similar.
The Approach posted by BlueRaja is slow I modified it as I was using to delete duplicates from the table. In case it helps anyone with large tables Original Query
This is taking more time:
Faster Solution
MariaDB has lifted this starting from 10.3.x (both for
DELETE
andUPDATE
):DBFiddle MariaDB 10.2 - Error
DBFiddle MariaDB 10.3 - Success
You can make this in three steps:
...
or
If you are trying to read fieldA from tableA and save it on fieldB on the same table, when fieldc = fieldd you might want consider this.
Above code copies the value from fieldA to fieldB when condition-field met your condition. this also works in ADO (e.g access )
source: tried myself
The problem is that MySQL, for whatever inane reason, doesn't allow you to write queries like this:
That is, if you're doing an
UPDATE
/INSERT
/DELETE
on a table, you can't reference that table in an inner query (you can however reference a field from that outer table...)The solution is to replace the instance of
myTable
in the sub-query with(SELECT * FROM myTable)
, like thisThis apparently causes the necessary fields to be implicitly copied into a temporary table, so it's allowed.
I found this solution here. A note from that article: