db.First(&user, "id = ?", "1b74413f-f3b8-409f-ac47-e8c062e3472a") // SELECT * FROM users WHERE id = "1b74413f-f3b8-409f-ac47-e8c062e3472a";
String条件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// 获得第一个符合条件的对象 db.Where("name = ?", "Yliken1").First(&user) // SELECT * FROM users WHERE name = 'jinzhu' ORDER BY id LIMIT 1;
// 查找所有的 db.Where("name <> ?", "Yliken1").Find(&users) // SELECT * FROM users WHERE name <> 'jinzhu';
// in db.Where("name IN ?", []string{"Yliken", "Yliken1"}).Find(&users) // SELECT * FROM users WHERE name IN ('Yliken','Yliken1');
// like db.Where("name LIKE ?", "%lik%").Find(&users) // SELECT * FROM users WHERE name LIKE '%lik%';
// and db.Where("name = ? AND age >= ?", "Yliken1", "22").Find(&users) // SELECT * FROM users WHERE name = 'Yliken1' AND age >= 22;
Struct & Map 条件
1 2 3 4 5 6 7 8 9 10 11
// 数据库中的 users 表中查找name =Yliken age =18 的用户 db.Where(&User{Name: "Yliken", Age: 18}).First(&user) // SELECT * FROM users WHERE name = "Yliken" AND age = 18 ORDER BY id LIMIT 1;
// 数据库中的 users 表中查找name =Yliken age =18 的用户 db.Where(map[string]interface{}{"name": "Yliken", "age": 18}).Find(&users) // SELECT * FROM users WHERE name = "Yliken" AND age = 18;
// 数据库中的 users 表中查找ID为20、21和22 的所有用户。 db.Where([]int64{20, 21, 22}).Find(&users) // SELECT * FROM users WHERE id IN (20, 21, 22);
Not 条件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//Not db.Not("name = ?", "Yliken").First(&user) // SELECT * FROM users WHERE NOT name = "Yliken" ORDER BY id LIMIT 1;
// Not In db.Not(map[string]interface{}{"name": []string{"Yliken", "Yliken1"}}).Find(&users) // SELECT * FROM users WHERE name NOT IN ("Yliken", "Yliken1");
// Struct形式 db.Not(User{Name: "Yliken", Age: 18}).First(&user) // SELECT * FROM users WHERE name <> "Yliken" AND age <> 18 ORDER BY id LIMIT 1;
// 不在某个主键集合中的记录 db.Not([]int64{1,2,3}).First(&user) // SELECT * FROM users WHERE id NOT IN (1,2,3) ORDER BY id LIMIT 1;