2012-04-11 313 views

回答

49

您可以爭辯說,SQLite根本不支持數據類型。例如,在SQLite3中,您可以執行此操作。

sqlite> create table test (id wibblewibble primary key); 

SQLite將很高興地創建一個具有「數據類型」wibblewibble的列。 SQLite也會很高興地創建具有「數據類型」uuid,guid和SuperChicken的列。

您的關鍵點可能是如何自動生成一個uid。 SQLite在那裏幫不了你。

您可以完全由客戶端程序決定。如果您使用python進行編程,請使用uuid module。在紅寶石中,你有SecureRandom.uuid function。其他語言具有相似的功能或變通方法。

你可以用C編寫你自己的用戶生成函數(參見Create or Redefine SQL Functions)。我會稱之爲相對極端的方法。

您可以將其存儲在binarytext格式中。


其他對話在線表明,有什麼一個UUID 一個普遍的誤解。一個UUID不僅僅是一個128位的隨機數。 UUID具有結構和規則。見RFC 4122

+1

感謝您的幫助。我爲android應用程序生成UUID,像這樣String sUUiDValue = UUID.randomUUID()。toString();然後插入表中... – amy 2012-04-19 10:06:02

3

這需要一個項目

select SUBSTR(UUID, 0, 8)||'-'||SUBSTR(UUID,8,4)||'-'||SUBSTR(UUID,12,4)||'-'||SUBSTR(UUID,16) 
from (
select lower(hex(randomblob(16))) AS UUID 
); 
+3

不幸的是,這會產生格式錯誤的UUID,例如:284e630-2293-bea6-21b1095ac11fe4f04。第一組應該有8個字符,第三組應該有4個字符,最後是12個字符。另外,UUID版本位應該是4,而不是隨機的。 – 2014-03-29 01:09:25

15

本傑明·貝瑞的答案是不正確的—它產生畸形的UUID —但它顯示了使用子查詢產生的隨機性然後從選擇子一個有趣的技術。下面是類似的東西,我已經確定沒有問題:

select substr(u,1,8)||'-'||substr(u,9,4)||'-4'||substr(u,13,3)|| 
    '-'||v||substr(u,17,3)||'-'||substr(u,21,12) from (
    select lower(hex(randomblob(16))) as u, substr('89ab',abs(random()) % 4 + 1, 1) as v); 

一些樣本輸出:

c71122df-18e4-4a78-a446-fbf7b8f2969b 
61e75f87-978b-4d9e-b587-bedcc2d23898 
30eee0fa-2ff2-4ff5-b8ef-f99378272999 
+1

對我來說,它創建了20個完全相同的uuids,用於從一個表到另一個表的遷移副本(其中我將_id從int更改爲此uuid) – miroslavign 2016-10-04 08:21:35

+1

與@miroslavign相同,如果在一個請求中用於更新所有表記錄,例如,生成要求與uuid相同的記錄。 – fharreau 2017-04-25 12:57:03

5

下面是類似的東西,可直接用作表達:

lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6))) 

爲要作爲列的默認值傳遞的示例:

sqlite> create table "table" (
    "id" char(36) default (lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))), 
    "data" varchar(255), primary key ("id") 
); 

sqlite> insert into "table" ("data") values ('foo'); 
sqlite> insert into "table" ("data") values ('bar'); 
sqlite> select * from "table"; 
947efcc9-4212-442a-b68c-eb6fbd8a7128|foo 
a2c3857b-1eb4-40bd-aed2-6e8d68cc2ab8|bar 
相關問題