2011-10-09 47 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

相關問題