SQLite语法文档显示在声明外键时可以指定“类型名称”。
https://www.sqlite.org/syntax/column-def.html
我无法找到任何地方,它与所指的键的“类型”有什么作用。当外键“type-name”与它所引用的值的“type-name”不匹配时会发生什么?它是否起任何作用,或只是为了可读性?
提前致谢。
答案 0 :(得分:1)
外键约束定义不包含类型名称。它可以附加到列定义,该列定义可以具有类型名称,但该类型名称属于列本身:
#standardSQL
WITH yourTable AS (
SELECT 1 AS user_id,'1a' AS visit_id, '2017-01-01 14:10:12' AS DATETIME,
'google cpc' AS channelgrouping, 0 AS transaction , 1 AS visit UNION ALL
SELECT 1, '1b', '2017-01-01 20:10:12', 'email', 1, 1 UNION ALL
SELECT 1, '1c','2017-01-03 08:10:12', 'direct', 0, 1 UNION ALL
SELECT 1, '1d','2017-01-04 13:10:14', 'organic', 1, 1 UNION ALL
SELECT 1, '1e','2017-03-04 13:10:14', 'organic', 0, 1 UNION ALL
SELECT 1, '1f','2017-03-04 13:10:14', 'direct', 0, 1
)
SELECT
user_id,
STRING_AGG(channelgrouping, ' > ' ORDER BY DATETIME) AS channelgrouping_path,
SUM(transaction) AS transaction,
SUM(visit) AS visits,
IF(SUM(transaction) = 0, NULL,
TIMESTAMP_DIFF(MAX(CAST(datetime AS TIMESTAMP)), MIN(CAST(datetime AS TIMESTAMP)), DAY)
) AS days_before_purchase
FROM (
SELECT
*,
SUM(transaction) OVER(PARTITION BY user_id ORDER BY datetime
ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
) AS grp
FROM yourTable
)
GROUP BY user_id, IFNULL(grp, 0)
上面显示的所有三列都有一个类型,但外键约束以CREATE TABLE Parent (
ID INTEGER PRIMARY KEY,
Name TEXT,
[...]
);
CREATE TABLE Child (
[...],
ParentID INTEGER REFERENCES Parent(ID)
-- column def. -- ---- foreign key ----
);
开头,并且不包含类型。
外键约束也可以写为表约束:
REFERENCES
这个表格很明显,约束没有单独的类型。
无论如何,SQLite使用dynamic typing并在大多数情况下忽略了类型名称,因此无论你在那里写什么,或者你根本不使用类型,都无关紧要。