Skip to content

Where的多重And和Or查询

Tuuz edited this page Jul 22, 2022 · 1 revision

本特性仅在GorosePro中单独支持,请勿在原版中使用,否则会导致错误!! 本特性仅在GorosePro中单独支持,请勿在原版中使用,否则会导致错误!! 本特性仅在GorosePro中单独支持,请勿在原版中使用,否则会导致错误!!

func Api_joinNoticeStatus_paginate_unread(student_id, school_id, year, class_id, gender, Type interface{}, limit, page int) gorose.Paginate {
	db := tuuz.Db().Table(Table)
	m1 := map[string]interface{}{}
	m2 := map[string]interface{}{}
	m3 := map[string]interface{}{}
	m4 := map[string]interface{}{}
	db.Fields(Table+".*", "ifnull(is_read,0) as is_read", "ifnull(is_del,0) as is_del", NoticeStatusModel.Table+".uid")
	m1[Table+".student_id"] = 0
	m2[Table+".student_id"] = 0
	m3[Table+".student_id"] = 0
	m4[Table+".student_id"] = student_id

	if school_id != nil {
		m1[Table+".school_id"] = school_id
		m2[Table+".school_id"] = school_id
		m3[Table+".school_id"] = school_id
		m4[Table+".school_id"] = 0
	}
	if year != nil {
		m1[Table+".year"] = year
		m2[Table+".year"] = year
		m3[Table+".year"] = 0
		m4[Table+".year"] = year
	}
	if class_id != nil {
		m1[Table+".class_id"] = class_id
		m2[Table+".class_id"] = 0
		m3[Table+".class_id"] = 0
		//m4[Table+".class_id"] = class_id
	}
	if gender != nil {
		//m1[Table+".gender"] = gender
		//m2[Table+".gender"] = gender
	}
	if Type != nil {
		m1[Table+".type"] = Type
		m2[Table+".type"] = Type
		m3[Table+".type"] = Type
		m4[Table+".type"] = Type
	}
	//db.OrWhere(m1)
	//db.OrWhere(m2)
	//db.OrWhere(m3)
	//db.OrWhere(m4)
	db.OrWhere([]interface{}{m1, m2, m3, m4})
	db.WhereNull("is_read")
	db.LeftJoin(NoticeStatusModel.Table, Table+".id=notice_id")
	db.Limit(limit)
	db.Page(page)
	//fmt.Println(db.Get())
	//fmt.Println(db.LastSql())
	//return gorose.Paginate{}
	ret, err := db.Paginator()
	if err != nil {
		Log.Dbrr(err, tuuz.FUNCTION_ALL())
		return gorose.Paginate{}
	} else {
		return ret
	}
}

这个查询将会生成如下语句:

SELECT
	ps_notice.*,
	ifnull( is_read, 0 ) AS is_read,
	ifnull( is_del, 0 ) AS is_del,
	ps_notice_status.uid 
FROM
	`ps_notice`
	LEFT JOIN ps_notice_status ON ps_notice.id = notice_id 
WHERE
	(
		( ps_notice.class_id = 1 AND ps_notice.student_id = 0 AND ps_notice.school_id = 1 AND ps_notice.YEAR = 2021 ) 
		OR ( ps_notice.student_id = 0 AND ps_notice.school_id = 1 AND ps_notice.YEAR = 2021 AND ps_notice.class_id = 0 ) 
		OR ( ps_notice.student_id = 0 AND ps_notice.school_id = 0 AND ps_notice.YEAR = 2021 AND ps_notice.class_id = 0 ) 
		OR ( ps_notice.student_id = 23 AND ps_notice.school_id = 1 AND ps_notice.YEAR = 2021 ) 
	) 
	AND ( is_read IS NULL ) 
	LIMIT 10;