1. 程式人生 > 資料庫 >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 ?

提示: 分散式影響

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對我們的支援。如果你想了解更多相關內容請檢視下面相關連結