mysql unique key在查詢中的使用與相關問題

今天小編就爲大家分享一篇關於mysql unique key在查詢中的使用與相關問題,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧

1、建表語句:

CREATE TABLE `employees` (
 `emp_no` int(11) NOT NULL,
 `birth_date` date NOT NULL,
 `first_name` varchar(14) NOT NULL,
 `last_name` varchar(16) NOT NULL,
 `gender` char(1) NOT NULL,
 `hire_date` date NOT NULL,
 PRIMARY KEY (`emp_no`),
 UNIQUE KEY `idxunique_first_name_gender` (`first_name`,`gender`),
 UNIQUE KEY `uniq_idx_firstname` (`first_name`,`gender`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

2、添加unique key:

-- 添加unique索引
alter table employees add constraint idxunique_first_name_gender unique(first_name, gender);

3、查詢測試語句:

-- 包含索引所有字段,且順序和索引一致
select * from employees where first_name='Chirstian' and gender='M';
-- key列值:idxunique_first_name_gender
-- 包含索引所有字段,但順序和索引不一致
select * from employees where gender='M' and first_name='Chirstian';
-- key列值:idxunique_first_name_gender
-- 包含索引第一個字段
select * from employees where first_name='Chirstian';
-- key列值:idxunique_first_name_gender
-- 包含索引的非第一個字段
select * from employees where gender='M';
-- key列值:NULL

4、在查詢時,如果where條件裏面只有unique key裏面的列(部分或者全部)且列值類型爲const。如果要使用unique key,where裏面必須得有建立unique key時的第一列,其他列隨意。

一個與mysql unique key相關的問題

xxx_tab的user_id是unique key, 來看看僞代碼:

get user_id=10000 from xxx_tab;
if exist 
{
  return ok
}
ret = insert user_id=10000
if ret ok 
{
  return ok
}
return not_ok

問題: 爲什麼最後結果是not_ok ?

提示: 分佈式影響

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對神馬文庫的支持。如果你想了解更多相關內容請查看下面相關鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章