如何简化以下SQL查询,
DECLARE @EMPLOYEE1 TABLE (EMPID INT,DEPT1 INT,DEPT2 INT)
DECLARE @EMPLOYEE2 TABLE (EMPID INT,DEPT1 INT,DEPT2 INT)
INSERT INTO @EMPLOYEE1 VALUES
(1,1,1),
(2,2,2),
(3,10,3),
(4,4,4)
INSERT INTO @EMPLOYEE2 VALUES
(1,1,1),
(2,2,2),
(3,10,10),
(4,10,4)
SELECT A.EMPID,
A.DEPT1 EMP1_DEPT,
0 TYPES
FROM @EMPLOYEE1 A
LEFT JOIN @EMPLOYEE2 B ON A.DEPT1=B.DEPT1
WHERE B.DEPT1 IS NULL
UNION ALL
SELECT A.EMPID,
A.DEPT2 EMP2_DEPT,
1 TYPES
FROM @EMPLOYEE1 A
LEFT JOIN @EMPLOYEE2 B ON A.DEPT2=B.DEPT2
WHERE B.DEPT2 IS NULL
任何人都可以解决这个问题,谢谢你提前
答案 0 :(得分:2)
这是一种方法:
Template.dash_board_content1.helpers({
'userTerritory': function(){
const territoryList = Template.instance().state.get('userTerritoryList');
if (territoryList) return territoryList;
Meteor.call('userTerritoryList', function(error,result){
if(!error){
Template.instance().state.set('userTerritoryList', result);
} else {
const errs = Template.instance().state.get('errors');
errs.push(error);
//update errors
Template.instance().state.set('errors', errs);
}
});
},
'getErrors' : function() {
//use in your template to display multiple err messages
return Template.instance().state.get('errors');
},
});
答案 1 :(得分:1)
以下是使用CROSS APPLY
和VALUES
的另一种选择:
SELECT A.EMPID,
A_D.DEPT AS 'EMP1_DEPT',
A_D.[TYPES]
FROM @EMPLOYEE1 A
CROSS APPLY (VALUES (A.DEPT1, 0), (A.DEPT2, 1)) A_D ( DEPT, [TYPES] )
WHERE NOT EXISTS (SELECT 1
FROM @EMPLOYEE2 B
CROSS APPLY (VALUES (B.DEPT1, 0), (B.DEPT2, 1)) B_D ( DEPT, [TYPES] )
WHERE B_D.DEPT = A_D.DEPT
AND B_D.[TYPES] = A_D.[TYPES]);
这种方法的优点是每个表只被击中一次。它使用NOT EXISTS
通过使用Left Anti Semi Join来提高查询计划的性能。