[英]Check if a value exists in a MySQL table
我的問題是我必須創建一個過程,該過程必須檢查表中是否存在某個值,如果確實存在,則必須從另一個表中刪除一些行。 到目前為止,我已經嘗試過select count(*) from (the select statement) as numOfRows;
的select count(*) from (the select statement) as numOfRows;
命令,但據我所見並在互聯網上搜索,它僅返回行數,而無法進一步使用它。
我對是否有辦法創建這樣的東西很感興趣:
if (the value exists in the table) then
-- do whatever it has to be done
歡迎任何想法! :)
記住要對語句進行參數化處理,以避免SQL注入,但是以下內容應為您提供一個總體思路。
delete from table_2
where id = @id
and exists ( select 1
from table_1
where id = @id )
我遇到了同樣的問題,並且以這種方式解決了(這不是最花哨的方式,但是它可行):
declare @InList int=0;
select @InList =count(*) FROM tblOne where fieldOne = @ValueOne
BEGIN TRAN
IF @InList > 0
BEGIN
IF EXISTS (SELECT * FROM tblTwo WHERE fieldTwo=@valueTwo)
BEGIN
Delete from tblTwo where fieldTwo=@valueTwo
END
END
COMMIT TRAN
問候,
MySQL的語法是否為:
SELECT IF(count(<field_in_question>), <do_this_if_true>, <do_this_if_false>)
FROM <your_table>
WHERE field_in_question='<some_value>'
您應該能夠選擇計數,如果計數大於0,則執行刪除操作或設置一個值,該值可在以后的過程中用於標記刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.