本文解答来自Monica ,记录学习过程。
衔接上一篇《sqlite3 如何创建一张新表并把某一栏绑定为其他表格的unique栏》
要通过外键约束访问 other_table
表格中的数据,您可以使用 SQL JOIN 语句将 new_table
和 other_table
表格连接起来。以下是一个示例 SQL 语句:
SELECT new_table.name, other_table.other_column
FROM new_table
JOIN other_table ON new_table.other_id = other_table.id
WHERE new_table.id = 1;
在这个示例中,我们使用 JOIN
语句将 new_table
和 other_table
表格连接起来,并使用 ON
子句将它们绑定在一起。我们将 new_table
表格中的 other_id
列与 other_table
表格中的 id
列进行匹配,以便获取与 new_table
表格中某个记录相关联的 other_table
表格中的数据。我们还使用 WHERE
子句来限制结果集,以便只返回与给定 ID 相关联的记录。
请注意,如果您要使用外键约束,请确保在打开数据库连接时启用外键支持。在 SQLite 中,您可以使用以下代码行来启用外键支持:
QSqlDatabase::database().exec("PRAGMA foreign_keys = ON;");