mysql unique key在查询中的使用与相关问题
1、建表语句:
CREATETABLE`employees`( `emp_no`int(11)NOTNULL, `birth_date`dateNOTNULL, `first_name`varchar(14)NOTNULL, `last_name`varchar(16)NOTNULL, `gender`char(1)NOTNULL, `hire_date`dateNOTNULL, PRIMARYKEY(`emp_no`), UNIQUEKEY`idxunique_first_name_gender`(`first_name`,`gender`), UNIQUEKEY`uniq_idx_firstname`(`first_name`,`gender`) )ENGINE=InnoDBDEFAULTCHARSET=utf8
2、添加uniquekey:
--添加unique索引 altertableemployeesaddconstraintidxunique_first_name_genderunique(first_name,gender);
3、查询测试语句:
--包含索引所有字段,且顺序和索引一致 select*fromemployeeswherefirst_name='Chirstian'andgender='M'; --key列值:idxunique_first_name_gender --包含索引所有字段,但顺序和索引不一致 select*fromemployeeswheregender='M'andfirst_name='Chirstian'; --key列值:idxunique_first_name_gender --包含索引第一个字段 select*fromemployeeswherefirst_name='Chirstian'; --key列值:idxunique_first_name_gender --包含索引的非第一个字段 select*fromemployeeswheregender='M'; --key列值:NULL
4、在查询时,如果where条件里面只有uniquekey里面的列(部分或者全部)且列值类型为const。如果要使用uniquekey,where里面必须得有建立uniquekey时的第一列,其他列随意。
一个与mysqluniquekey相关的问题
xxx_tab的user_id是uniquekey,来看看伪代码:
getuser_id=10000fromxxx_tab; ifexist { returnok } ret=insertuser_id=10000 ifretok { returnok } returnnot_ok
问题:为什么最后结果是not_ok?
提示:分布式影响
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接