我想在插入值时忽略或更新重复项。我知道on duplicate key
,但我无法找到解决方案。这是示例表示例。
| ID | roll | sub | mark |
| ---- |----------| ------|------|
| 1 | 100 | 11 | 15 |
| 2 | 101 | 11 | 16 |
| 3 | 102 | 11 | 17 |
| 4 | 100 | 12 | 10 |
| 5 | 101 | 12 | 11 |
| 6 | 102 | 12 | 12 |
此处id
为primary key
,但我想插入以检查roll & sub
是否已存在,然后更新,否则插入新行。我尝试使用以下代码,但是插入了重复的行,但它应该更新下表中的第6行。
CREATE INDEX mycompo_index on student(roll,sub);
insert into student(roll, mark, sub)
values (102, 22, 12)
on duplicate key update mark = values(mark);
答案 0 :(得分:2)
如果sub
和ALTER TABLE student ADD CONSTRAINT student_uq UNIQUE(roll, sub)
的组合应该是唯一的,您应该在表格中定义这样一个键:
on duplicate key
请注意,如果您这样做,则不必显式创建您正在创建的索引,该约束将为您创建。一旦有了这个地方,您可以使用您尝试使用的INSERT INTO student(roll, mark, sub)
VALUES (102, 22, 12)
ON DUPLICATE KEY UPDATE mark = VALUES(mark)
语法:
#Script to solve F issue
#----------------------------------------
#By Kapil Shirsath
#----------------------------------------
cd /var/spool/mail #mail files reside in mail folder
filename=`ls -l | grep '^-' | sort -k 5 -rn | head -1 | tr -s " " "," | cut -d "," -f "9"` # this will list the file with maximum size`
echo "File with maximum size is $filename"
echo "----------------------------------------------------"
echo "Is it the file expected?(y/n)"
read choice
if test $choice == "n"
then
echo "Exiting...."
exit;
fi;
c=1
while [ $c -le 5 ]
do
ls -l $filename
echo $filename
sleep 2
c=`expr $c + 1`
done
echo "---------------------------------------------------"
#`sudo su` #this will give you super user permissions
echo "First line of the file is as below :"
head -1 $filename
echo "---------------------------------------"
firstline=`head -1 $filename`;
echo "Repeat : $firstline"
echo $firstline | grep ^"rom" >/dev/null
if test $? -eq 0
then
ex -s $filename <<'EOF'
1s/^/F/
:wq
EOF
echo "F issue fixed!"
c=1
while [ $c -le 5 ]
do
ls -l $filename
sleep 2
c=`expr $c + 1`
done
echo "---------------------------------------------------"
else
echo "Not finding the missing 'F' ! !! Kindly check with your system "
exit;
fi;