I want to set 'isSomething' to 1 if the 'foo' is in column1 values, else 'isSomething' is 0
The problem is: the same query gives different result from console and from a trigger.
And the console version gives good result.
(everything is the same in the subquery, in the trigger I always get the same New.id! - test case)
-----TRIGGER (AFTER UPDATE)
...
DECLARE isSomething INT DEFAULT 0;
select if('foo' IN (select column1 from ...where id=NEW.id),1,0)
INTO isSomething;
...
LOG: isSomething:0
-----CONSOLE
select if('foo' IN (select column1 from ...where id=232),1,0)
into #isSomething;
select #isSomething;
...
CONSOLE: 1 (good result!!!)
COMMENT: i tried the following query as well
select count(*) into isSomething from ... where id = NEW.id and column1='foo'
And it behaves like the first query.
UPDATE 1
Interesting the 2nd type of query without "and column1='foo'"
select count(*) into isSomething from ... where id = NEW.id
Gives right result:3, as if 'foo' wouldnt be in the result.
SOLUTION
I dont know why, but if I use table alias (here:ft), then the query works and the result is good ...
select count(*)
into isSomething
from footable ft WHERE ft.column1 = 'foo' AND ft.id = NEW.id ....;
Thanks for everyone the effort!
Cs.
Related
I`m trying to delete a lot of data via select. This select work appropriate and returns in result 75k+ rows. I need to delete them, but when I try to delete it this error occurs
#1241 - Operand should contain 1 column(s). I'm using PHPMyAdmin.
DELETE FROM `crm_wsal_metadata`
WHERE `occurrence_id` = ANY
(SELECT *
FROM `crm_wsal_metadata`
WHERE `name` = `PostDate` AND `value` BETWEEN str_to_date('2018-12-26', '%Y-%m-%d') AND str_to_date('2020-05-31', '%Y-%m-%d')
GROUP BY `occurrence_id`)
Use
... SELECT `occurence_id` ...
instead of SELECT *. The group by clause forces you to use only grouped columns and aggregations, not star (perhaps unless some proprietary quirks I don't recommend to rely on).
I had found the answer and will try to write it step by step:
Why does this error happen?
In MySQL, you can't modify the same table which you use in the SELECT part.
This behavior is documented at http://dev.mysql.com/doc/refman/5.6/en/update.html
How to make such thing happen?
There are two ways:
Join the table to itself
UPDATE tbl AS a
INNER JOIN tbl AS b ON ....
SET a.col = b.col
Nest the subquery deeper into a from clause
UPDATE tbl SET col = (
SELECT ... FROM (SELECT.... FROM) AS x);
Personally, in my case the code looked like this:
DELETE FROM crm_wsal_metadata
WHERE occurrence_id = ANY (
SELECT occurrence_id FROM (
SELECT occurrence_id FROM crm_wsal_metadata WHERE name = "PostDate" AND value BETWEEN str_to_date('2018-12-26', '%Y-%m-%d') AND str_to_date('2020-05-31', '%Y-%m-%d') AS search) )
Sorry for such bad styling. Im new with it :)
This must be fairly straight forward, as I tend to use ORMs I don't have to get my hands dirty often and am therefore struggling!
I have a database and want to get several fields from a table, that bit is easy..
SELECT main_table.registration_number, main_table.registered_name FROM main_table;
I want to filter the results based on another table, which is also easy..
SELECT second_table.registration_number FROM second_table WHERE this_field = '' AND that_field = '0';
Now the problem is I want to run the first query based on the second queries result set, I was thinking something like this:
SELECT main_table.registration_number, main_table.registered_name FROM main_table WHERE main_table.registration_number IN (SELECT * FROM second_table WHERE this_field = '' AND that_field = '0');
This gives me: Error Code: 1241. Operand should contain 1 column(s)
Am I handling this completely wrong?
Your subquery should do something like below,
(select * from table) in subquery is not what you really need to do your
so the subquery should return one column
(SELECT registration_number FROM second_table WHERE this_field = '' AND that_field = '0');
You cannot have multiple columns being returned in a subquery like
that, doing so it will result in such error
You have to select a column
SELECT main_table.registration_number, main_table.registered_name FROM
main_table WHERE main_table.registration_number IN (SELECT
registration_number FROM second_table WHERE this_field = '' AND
that_field = '0');
Lets say I have a table, myTable, like this:
ID1 Value ID2
1 6.5064 3
2 7.9000 3
3 9.9390 3
4 8.6585 3
What I'm trying to do is SELECT each of those Value's for a given ID2. However, the number of rows returned for Value can change. So, if ID2 = 2, only 1 row might get returned. If drID = 4, 3 rows might get returned.
The part of my query that is trying to handle this is nested, so when I run it I get a "Subquery returns more than 1 row" error. Any idea how I can select a variable number of rows in this way?
Thanks in advance!
Edit: here is what I have so far, and the commented out portion is what I expected to select those values for me, but it throws the above mentioned error:
SELECT drDateTime AS Date,
(SELECT fncName FROM functionlist
WHERE datarecord.fncID = functionlist.fncID) AS FunctionName,
(SELECT alText FROM alarmlevellist
WHERE datarecord.alID = alarmlevellist.alID) AS AlarmDescription
#(SELECT rdValue FROM rawdata
#WHERE datarecord.drID = rawdata.drID)
FROM datarecord
WHERE alID IS NOT NULL AND drSumFlag = 1;
You should show your query.
One common place this problem occurs is in where (or having) clauses. A solution to this problem is to use in rather than =, if the subquery is in the where clause. If you have something like:
where id = (select id2 . . .)
Then change it to:
where id in (select id2 . . .)
Use a join instead of a subquery. I would probably use a join for all tables but that is up to you.
SELECT drDateTime AS Date,
(SELECT fncName FROM functionlist WHERE datarecord.fncID = functionlist.fncID) AS FunctionName,
(SELECT alText FROM alarmlevellist WHERE datarecord.alID = alarmlevellist.alID) AS AlarmDescription,
rawData.drID
FROM datarecord
INNER JOIN rawdata
ON datarecord.drID = rawdata.drID)
WHERE alID IS NOT NULL AND drSumFlag = 1;
I am trying this query but it outputs a syntax error in the subquery.
What is the problem and how can be solved? thanks
UPDATE CompradorCategorias_new as A
SET A.idParent=(
SELECT idcategoria
FROM categoriasi18n_new
WHERE
(
SELECT SUBSTRING_INDEX(NomeComPath, '>', 2)
FROM CompradorCategorias_new
=
SELECT translationWithPath
FROM categoriasi18n_new
)
)
Everything looks good in your query until the WHERE clause - at that point, it's all kinds of wrong. You can actually drop that block and use a regular WHERE clause comparison (instead of a second sub-query):
UPDATE
CompradorCategorias_new AS A
SET
A.idParent = (
SELECT
idcategoria
FROM
categoriasi18n_new AS B
WHERE
B.translationWithPath = SUBSTRING_INDEX(A.NomeComPath, '>', 2)
)
Here are two statements that I'd like to work, but which return error messages:
IF EXISTS (SELECT * FROM gdata_calendars WHERE `group` = ? AND id = ?) SELECT 1 ELSE SELECT 0
and
IF ((SELECT COUNT(*) FROM gdata_calendars WHERE `group` = ? AND id = ?) > 0) SELECT 1 ELSE SELECT 0;
The question marks are there because I use parametrized, prepared, statements with PHP's PDO. However, I have also tried executing this with data manually, and it really does not work.
While I'd like to know why each of them doesn't work, I would prefer to use the first query if it can be made to work.
You cannot use IF control block OUTSIDE of functions. So that affects both of your queries.
Turn the EXISTS clause into a subquery instead within an IF function
SELECT IF( EXISTS(
SELECT *
FROM gdata_calendars
WHERE `group` = ? AND id = ?), 1, 0)
In fact, booleans are returned as 1 or 0
SELECT EXISTS(
SELECT *
FROM gdata_calendars
WHERE `group` = ? AND id = ?)
I found the example RichardTheKiwi quite informative.
Just to offer another approach if you're looking for something like IF EXISTS (SELECT 1 ..) THEN ...
-- what I might write in MSSQL
IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='')
BEGIN
SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
INSERT INTO TABLE(FieldValue) VALUES('')
SELECT SCOPE_IDENTITY() AS TableID
END
-- rewritten for MySQL
IF (SELECT 1 = 1 FROM Table WHERE FieldValue='') THEN
BEGIN
SELECT TableID FROM Table WHERE FieldValue='';
END;
ELSE
BEGIN
INSERT INTO Table (FieldValue) VALUES('');
SELECT LAST_INSERT_ID() AS TableID;
END;
END IF;
The accepted answer works well and one can also just use the
If Exists (...) Then ... End If;
syntax in Mysql procedures (if acceptable for circumstance) and it will behave as desired/expected. Here's a link to a more thorough source/description: https://dba.stackexchange.com/questions/99120/if-exists-then-update-else-insert
One problem with the solution by #SnowyR is that it does not really behave like "If Exists" in that the (Select 1 = 1 ...) subquery could return more than one row in some circumstances and so it gives an error. I don't have permissions to respond to that answer directly so I thought I'd mention it here in case it saves someone else the trouble I experienced and so others might know that it is not an equivalent solution to MSSQLServer "if exists"!
If your table has an auto-incrementing primary key, you can use REPLACE INTO ... VALUES
SELECT #id := id FROM tableName WHERE fieldName='criteria value' LIMIT 1;
REPLACE INTO tableName(id, fieldName, col1, col2)
VALUES (#id, 'criteria value', 'value1', 'value2')
If the select statement returns NULL, then a new row is inserted.
Otherwise, if a row is found, it will update the row with key #id.
SELECT IF((
SELECT count(*) FROM gdata_calendars
WHERE `group` = ? AND id = ?)
,1,0);
For Detail explanation you can visit here