1. 程式人生 > >UPDATE與多表關聯更新

UPDATE與多表關聯更新

SQL環境:SQL Server 2008

業務需求:將查詢的記錄集合更新部分欄位,涉及到多張表

1.SQL查詢獲得的記錄集合:

SELECT u.USER_NAME_,g.desc_, u.email_, u.mobile_
FROM BDF2_GROUP g, BDF2_GROUP_MEMBER gm, UBP_USER u
where g.id_=gm.group_id_ and gm.username_=u.user_name_
AND g.desc_ IN (
		'310115-02', 
		'310118-02', 
		'310112-02'
	)
	
	
order by u.USER_NAME_

2.將原有SQL轉化成等價的SQL【採用SQL子查詢】

SELECT USER_NAME_, email_, mobile_
FROM UBP_USER
WHERE USER_NAME_ IN (
	SELECT username_
	FROM BDF2_GROUP_MEMBER
	WHERE group_id_ IN (
		SELECT id_
		FROM BDF2_GROUP
		WHERE desc_ IN (
			'310115-02', 
			'310118-02', 
			'310112-02'
		)
	)
)
ORDER BY USER_NAME_

3.SQL修改一張表部分欄位【查詢時涉及多張表

UPDATE UBP_USER
SET email_ = '[email protected]', mobile_ = '11111111111'
WHERE USER_NAME_ IN (
		SELECT username_
		FROM BDF2_GROUP_MEMBER
		WHERE group_id_ IN (
			SELECT id_
			FROM BDF2_GROUP
			WHERE desc_ IN (
				'310115-02', 
				'310118-02', 
				'310112-02'
			)
		)
	)