-1
good afternoon, I need to understand how an if works inside mysql to be able to use as follows.
I have a foreach that only executes after a database select because it leaves an array for this foreach, in this foreach it will run a condition, if a column exists it will insert information into it, if it does not exist it will create the column and then insert information in it, the problem is, if I send two columns of the same name it will create the first and insert in the second will generate error because the column exists, how to see if the column exists before creating without having to do another query and another loop?
SELECT column_name FROM information_schema.COLUMNS
WHERE column_name = 'telefone' AND TABLE_NAME = 'usr_9f8b498a8e2976d3'
SELECT COUNT(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'usr_9f8b498a8e2976d3' AND COLUMN_NAME = 'telefone'
in these two selects I can bring if there is or not the column, the bottom is faster, in case, I would like at the end of these selects, in the same query, if der TRUE does not create the column but if der false then create the column
sort of like this /a/3774/8939
something like this, only in mysql that works
IF (SELECT COUNT(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'usr_9f8b498a8e2976d3' AND COLUMN_NAME = 'telefone') THEN
BEGIN
select * from usr_9f8b498a8e2976d3
END;
ELSE
BEGIN
select * from usr_9f8b498a8e2976d3
END;
END IF;
I found this code which is exactly how I want it, but I can’t execute alter table and Insert into inside true and false, but true and false work exactly as wish, is there a way to run alter tabble inside true and Insert into false? in case false has to run both alter table and Insert into and true only Insert into
SELECT IF((SELECT COUNT(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'usr_9f8b498a8e2976d3' AND COLUMN_NAME = 'sobrenome'),(
'true'
),(
'false'
))
Please avoid long discussions in the comments; your talk was moved to the chat
– Maniero