如何根据其他列值设置唯一约束

时间:2017-08-19 04:20:14

标签: sqlite

我为客户域维护编写了以下脚本。在我想要在表中修改的脚本中。如果状态是活动的,我想设置唯一约束到端口字段.else如果状态为非活动我不想要唯一约束。我可以根据其他列值设置此约束吗?请帮帮我..!

    #!/bin/bash

echo " --- Enter the Database name ---" #name of the database
read databasename

echo " --- enter the table name --- " #name of the table
read table_name

sqlite3 $databasename.db "DROP TABLE IF EXISTS $table_name;"

sqlite3 $databasename.db  "CREATE TABLE IF NOT EXISTS $table_name(cus_id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,cus_name TEXT NOT NULL UNIQUE ,cus_domain TEXT UNIQUE,Created_on default CURRENT_DATE,cus_status TEXT NOT NULL,Port INTEGER NOT NULL);" #table creation


echo " --- Enter the total number of customer records do you want ---"
read cus_count # number of rows value


echo "--- Enter the following details one by one---"

RED='\033[0;31m'
NC='\033[0m'
port_num=8080
declare -a customer

for((i=1;i<=cus_count;i++))
do


echo "enter the $i customer details"

echo "---Enter the customer name---"
read c_name

d_name=${c_name,,}
#echo $d_name

customer=$(sqlite3 $databasename.db "select cus_domain from $table_name where cus_domain like '$d_name';")

for cus in "${customer[@]}"
do

if [[ $d_name != $customer ]];

then
    echo "---Enter the Status(Active/Inactive)---"
    read c_status

if [[ "$port_num" == "$port_num" ]]; then
       port_num=$(($port_num + 1))

c_domain="$c_name"


sqlite3 $databasename.db "INSERT OR IGNORE INTO $table_name (cus_name,cus_domain,cus_status, Port) VALUES(\"$c_name\",\"${c_domain,,}\",\"${c_status,,}\",\"$port_num\") ;" 
fi


else
    echo -e "${RED}!!!OOPS for you entered customer name already  domain name assigned!!!${NC}"
    echo -e "${RED}Please enter new customer name${NC}"

i=$(($i - 1))

fi
done
done

echo " --- Records from the $table_name ---"

sqlite3 $databasename.db "select * from $table_name;"

1 个答案:

答案 0 :(得分:1)

使用partial index

  

部分索引定义可能包含UNIQUE关键字。如果是,则SQLite要求索引中的每个条目都是唯一的。这提供了一种机制,用于在表的某些行子集中强制实现唯一性。

CREATE UNIQUE INDEX i ON MyTable(Port) WHERE cus_status = 'Active';