[英]Write an update query only if a column exists in a mysql table through a bash script file
我有一個 bash script.sh 文件,其中我正在訪問一個 MySQL 數據庫,其中包含一個名為“Foo”的表。 我在使用 MySQL 語法來執行更新查詢以設置“Bar”列中的值時遇到問題,僅當“Bar”存在於表“Foo”中時,否則更新“Foo”中其他列中的值而沒有列“Bar” . if/else 語句通過訪問 MySQL 命令行界面和我已經擁有的更新查詢本身的包裝器提供。
如果可能,我想避免創建過程或 function。
現在,if/else 看起來像這樣:
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='Foo' AND
column_name='Bar') THEN
//UPDATE Foo SET Bar query
ELSE
//UPDATE Foo without column Bar
END IF;
我已經搜索了幾個小時,但仍然遇到以下查詢錯誤:
Query Error: Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='Foo' AN' at line 1
您可以在腳本本身中進行查詢。
cols=$(mysql -e "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='Foo' AND column_name='Bar'")
if [[ $cols -eq 1 ]]
then
# perform update with column Bar
else
# perform update without column Bar
fi
您可能希望通過 bash 腳本中的幾個步驟來執行此操作。 首先執行以下操作:
# Create and populate a variable named exists
exists=$(mysql -e "Select 0 from information_schema.columns where...")
# Check to see if $exists is empty/null in bash.
# Do the appropriate update query based on the if statement.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.