Mysql 如果引用表中的值为null或零,则取消插入

Mysql 如果引用表中的值为null或零,则取消插入,mysql,sql,Mysql,Sql,我有两个相互关联的表。引擎:myisam 1: 2: 如您所见,项目有一列items\u account\u ID。每一件物品都属于一个人 账户要插入项目,我使用如下查询: INSERT INTO items SET items_name = 'asd', items_account_ID = (SELECT account_ID FROM account WHERE account_ID = accountValue AND account_pwd='something'); 此查询是在as

我有两个相互关联的表。引擎:myisam

1:

2:

如您所见,项目有一列
items\u account\u ID
。每一件物品都属于一个人 账户要插入项目,我使用如下查询:

INSERT INTO items SET items_name = 'asd', items_account_ID = (SELECT account_ID FROM account WHERE account_ID = accountValue AND account_pwd='something');
此查询是在asp.net中创建的,accountValue来自某个对象的会话或隐藏字段。SELECT语句是出于安全原因,因此用户不能为彼此创建项

如果帐户ID不存在,我想取消插入的
。比如:

..“items\u account\u ID=IFNULL(selectstatement,“cancelQuery()”)

但是我在mysql中找不到任何取消当前查询的函数。

这可能吗?

首先,您应该将
项目\u帐户\u ID
定义为
不为空
,并确保它引用
帐户(帐户\u ID)
作为外键。这样做可以防止您将坏的
帐户\u ID
插入
项目中

您可以考虑将插入重写如下:

insert items 
(
     items_name
    ,items_account_ID
)
select
'asd'
,account_ID
from account 
where account_ID = accountValue 
and account_pwd = 'something'

感谢您的回复。这听起来是一个很好的方法,没有想到选择所有值。谢谢!即使没有
外键
声明(需要将表从MyISAM更改为InnoDB才能工作),这也可以工作。即使如此,他仍然应该正确地实现他的关系。
INSERT INTO items SET items_name = 'asd', items_account_ID = (SELECT account_ID FROM account WHERE account_ID = accountValue AND account_pwd='something');
insert items 
(
     items_name
    ,items_account_ID
)
select
'asd'
,account_ID
from account 
where account_ID = accountValue 
and account_pwd = 'something'