sqlite - 选择所有不在相关表中的

标签 sqlite go go-gorm

例如,我在表中有以下 gorm 对象。

user
+----+------+
| id | name |
+----+------+
| 1  | John |
+----+------+
| 2  | Jane |
+----+------+

phones
+----+------+
| id |number|
+----+------+
| 1  | 0945 |
+----+------+
| 2  | 0950 |
+----+------+
| 3  | 1045 |
+----+------+

user_phones
+----+-------+--------+
| id |user_id|phone_id|
+----+-------+--------+
| 1  | 1     | 1      |
+----+-------+--------+
| 2  | 1     | 2      |
+----+-------+--------+
| 3  | 2     | 3      |
+----+-------+--------+

对于 gorm,我想选择所有未给定用户的电话。 类似于:选择 * phones where user_phones.user_id != 1 这就是我的尝试:

Gdb.Order("id desc").Where("status = ?", true).Find(&phones).Related("UserPhones").Not("UserPhones.User.ID = ?", user.ID)

最佳答案

我使用连接而不是 gorm 的相关让它工作。也许不是惯用的 gorm,但我在 gorm 中的高级关系中从来没有任何运气。

Gdb.LogMode(true)

if err := Gdb.Joins("left join user_phones on phones.id=user_phones.phone_id").Order("id desc").Where("status = ?", true).Not("user_phones.user_id = ?", user.Id).Find(&phones).Error; err != nil {
    fmt.Printf("%v\n", err)
} else {
    fmt.Printf("result = %+v\n", phones)
}

这会产生以下 SQL:

SELECT  `phones`.* FROM `phones` left join user_phones on phones.id=user_phones.phone_id WHERE (status = 'true') AND NOT (user_phones.user_id = '1') ORDER BY id desc

并输出:

result = [{Id:3 Number:1045}]

我习惯使用 mysql,但我看不出 sqlite 有什么不同。

关于sqlite - 选择所有不在相关表中的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39964882/

相关文章:

mysql - sql计算多行类里面的当前学生

android - sqlite 函数在给定日期中显示月份?

c++ - 如何使用 QsqlQuery 获取最后准备和执行的查询?

go - 如何使用 go mod 复制非 go 文件

使用 golangci 执行命令安全 linting 消息

go - 使用 GORM 将接口(interface)设置为具有许多实现的属性

python - 将多个html文件抓取到CSV

go - 两个软件包之间的 channel 通信陷入僵局-Golang

mysql - 如何在 Jinzhu GORM 中创建 Left Join

mysql - 默认时间戳在不同的mysql表中具有不同的时区