我工作的公司使用第三方软件,我们没有接触过应用程序代码,因此我无法更改数据库对象。 我试图在一个不是Sarg的视图中做一些工作,在视图中有一个colesce将null替换为0,并且在应用程序上调用视图,同一列上有一个过滤器。
方案如下:
var arr = [{ "Id": 46489,
"Message": "Hi",
"MessageGroupId": 46488,
"FlowId": 99
},
{
"Id": 46492,
"Message": "Hi User",
"MessageGroupId": 46490,
"FlowId": 100
},
{
"Id": 46494,
"Message": "Loan",
"MessageGroupId": 46490,
"FlowId": 101
},
{
"Id": 46496,
"Message": "Call",
"MessageGroupId": 46490,
"FlowId": 101
}
]
Array.prototype.groupBy = function (props) {
var arr = this;
var partialResult = {};
arr.forEach(el=>{
var grpObj = {};
props.forEach(prop=>{
grpObj[prop] = el[prop]
});
var key = JSON.stringify(grpObj);
if(!partialResult[key]) partialResult[key] = [];
partialResult[key].push(el);
});
var finalResult = Object.keys(partialResult).map(key=>{
var keyObj = JSON.parse(key);
keyObj.values = partialResult[key];
return keyObj;
})
return finalResult;
}
console.log(arr.groupBy(['MessageGroupId','FlowId']))
第一次测试 - Sarg问题
IF OBJECT_ID('test01' , 'U') IS NOT NULL
DROP TABLE test01;
CREATE TABLE test01 ( ID INT IDENTITY(1,1) PRIMARY KEY
, Parent NVARCHAR(100)
);
GO
IF OBJECT_ID('test02' , 'U') IS NOT NULL
DROP TABLE test02;
CREATE TABLE test02 ( ID INT IDENTITY(1,1) PRIMARY KEY
, ParentID INT
, UserName NVARCHAR(100)
);
GO
ALTER TABLE test02 ADD CONSTRAINT FK_test02_ParentID FOREIGN KEY (ParentID) REFERENCES test02(ID);
INSERT INTO test01
SELECT 'DGN010101'
UNION ALL SELECT 'DGN020202'
UNION ALL SELECT 'DGN030303'
UNION ALL SELECT 'DGN040404'
GO
INSERT INTO test02 (ParentID, UserName)
SELECT 1, 'DGN010101'
UNION ALL SELECT 2, 'DGN020202'
UNION ALL SELECT NULL, 'DGN030303'
GO
第二次测试 - 没有sarg问题
--drop view vw_test
CREATE VIEW vw_test
AS
SELECT tmp1.ID as ParentID
, tmp1.Parent
, COALESCE(tmp2.ID, 0) as UserID
, tmp2.UserName
FROM test01 tmp1
LEFT JOIN test02 tmp2
on tmp1.ID = tmp2.ID
------------------------
-- An index scan is performed
SELECT ParentID
, Parent
, UserID
, UserName
FROM vw_test
WHERE UserID = 1
要记住的事情:
我很感激你们的想法。
答案 0 :(得分:2)
如果test02表的ID列(UserID)不允许NULL,请尝试以下版本:
CREATE VIEW vw_test2
AS
SELECT tmp1.ID as ParentID
, tmp1.Parent
, tmp2.ID as UserID
, tmp2.UserName
FROM test01 tmp1
JOIN test02 tmp2
on tmp1.ID = tmp2.ID
UNION ALL
SELECT tmp1.ID as ParentID
, tmp1.Parent
, 0 as UserID
, tmp2.UserName
FROM test01 tmp1
LEFT JOIN test02 tmp2
on tmp1.ID = tmp2.ID
WHERE tmp2.ID IS NULL;
GO