Hello stackoverflow members.
First, I'm new to SQL and have almost only theory knowledge about databases. This is the table:
create table ACCOUNT (LOGIN varchar (16) primary key, MAIN boolean not null);
Now I have created this procedure for inserting a new tuple:
delimiter $$
create procedure add_account (in login varchar (16))
begin
declare main boolean;
set main = not exists (select LOGIN from ACCOUNT where MAIN);
insert into ACCOUNT (LOGIN, MAIN) values (login, main);
end
$$
delimiter ;
My intention: By using add_account
, only one tuple in ACCOUNT
has the value true
for attribute MAIN
. But after that, it seems that the NOT EXISTS
is always true:
call add_account ('First');
call add_account ('Second');
select * from ACCOUNT;
+--------+------+
| LOGIN | MAIN |
+--------+------+
| First | 1 |
| Second | 1 |
+--------+------+
The second should be 0 because there is already a tuple that is 1. Anyone got ideas? What is wrong about my code/thinking?
Thanks in advance and Greetings
After Gordon's answer, I renamed the lower-case main
to foo
. My wrong thinking: I thought that lower-case main
would be seen as different from upper-case MAIN
. Now the results are as I wished:
call add_account ('First');
call add_account ('Second');
select * from ACCOUNT;
+--------+------+
| LOGIN | MAIN |
+--------+------+
| First | 1 |
| Second | 0 |
+--------+------+
答案 0 :(得分:2)
Let me explain this logic, line by line:
declare main boolean;
set main = not exists (select LOGIN from ACCOUNT where MAIN);
insert into ACCOUNT (LOGIN, MAIN) values (login, main);
Line 1 declares a variable called main
as a boolean. By default, the value will be NULL
, which is treated as false.
Line 2 runs the following query:
select LOGIN
from ACCOUNT
where MAIN
Well, MAIN
is NULL
-- basically "false" -- hence this returns no values. So, the NOT EXISTS
returns "true", which is then assigned to main
Line 3 inserts the new value in the row.
This is clearly not your intention. I would suggest that you ask another question and describe what you want to do, along with sample data and desired results.