2011-10-09 50 views
1

我有几个相互关联的表。引擎:MyISAM的如果参考表中的值为空或零,则取消INSERT

1:

account 
account_ID, account_username, account_pwd, ...... 

2:

items 
items_account_ID, items_name, ...... 

正如你所看到的,物品具有一列items_account_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语句出于安全原因,因此用户不能为彼此创建项目。如果account_ID不存在,我想取消INSERT。喜欢的东西:

......” items_account_ID = IFNULL(theSelectStatement, “cancelQuery()”);

但我不能在mysql中找到任何功能取消当前查询
这是可能的。 ?

回答

3

首先,你应该定义为items_account_IDnot null确保它引用account(account_ID)作为外键。这样做会防止你插入一个坏account_IDitems

然后你可以考虑重写你的插入如下:

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

感谢您的回复。这听起来像是一个很好的做法,没有想到选择所有的值。谢谢! – Easyrider

+0

即使没有'FOREIGN KEY'声明(这将需要更改表格MyISAM到InnoDB的工作),这也可以工作。 –

+0

即使如此,他仍然应该正确地执行他的关系。 – canon

相关问题