Cancel INSERT if value in referenced table is null or zero
I have a couple of tables that are related to each other. engine: myisam
1:
account
account_ID, account_username, account_pwd, ......
2:
items
items_account_ID, items_name, ......
As you can see, items have a column items_account_ID
. Every item belongs to an
account. To insert an item I use a query like:
INSERT INTO items SET items_name = 'asd', items_account_ID = (SELECT account_ID FROM account WHERE account_ID = accountValue AND account_pwd='something');
This query is created in asp.net and accountValue is from SESSION or hidden field of something. the SELECT statement is for security reasons so that users can't create items for each other.
I would like to cancel the INSERT
if the account_ID doesn't exist. Something like:
...." items_account_ID = IFNULL(theSelectStateme开发者_Python百科nt, "cancelQuery()");
But I can't find any function in mysql to cancel the current query.
Is this possible?First of all, you ought to define items_account_ID
as not null
and make sure it references account(account_ID)
as a foreign key. Doing so will prevent you from inserting a bad account_ID
into items
.
Then you might consider rewriting your insert as follows:
insert items
(
items_name
,items_account_ID
)
select
'asd'
,account_ID
from account
where account_ID = accountValue
and account_pwd = 'something'
精彩评论