INSERT INTO...SELECT...WHERE 如果条件失败则为 null

发布于 2025-01-03 17:46:38 字数 330 浏览 2 评论 0原文

我正在尝试执行类似以下操作:

INSERT INTO `File` (`Name`, `Owner`) 
SELECT @File, `Users`.Id
FROM `Users`
WHERE `Users`.`Name` = @UserName

但是,如果 Users 表中没有匹配项,我希望它仍然插入文件但具有空值。就像在 Users 表上执行 LEFT JOIN 一样,用 ON 替换 WHERE。但我不能只使用 LEFT JOIN,因为我没有可以连接它的表。谁能帮我解决如何在不将其分成两个单独的查询的情况下做到这一点?

这是专门针对 SQLite 的。

I'm attempting to do something like the following:

INSERT INTO `File` (`Name`, `Owner`) 
SELECT @File, `Users`.Id
FROM `Users`
WHERE `Users`.`Name` = @UserName

However, if there is no match in the Users table, I would like it to still insert the file but with a null value. So like performing a LEFT JOIN on the Users table with ON replacing the WHERE. But I can't just use a LEFT JOIN because I don't have a table to join it to. Can anyone help me out in how I could do this without breaking it into two separate queries?

This is specifically for SQLite.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

亚希 2025-01-10 17:46:38

也许这样的事情可以解决问题:

INSERT INTO `File` (`Name`, `Owner`) 
SELECT @File, `Users`.Id
FROM (SELECT @UserName as Name) notable
left join `Users` on `Users`.`Name` = notable.Name

Maybe something like this could do the trick:

INSERT INTO `File` (`Name`, `Owner`) 
SELECT @File, `Users`.Id
FROM (SELECT @UserName as Name) notable
left join `Users` on `Users`.`Name` = notable.Name
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文