我有一種情況,即從多個表MEMBERS,SS和SSUSED撤回數據。其中'MEMBERS'是成員數據表,'SS'是成員在其賬戶上購買的產品表,SSUSED是存儲產品使用情況的表格。產品可以有1,6或12個用途。所以可以有一對一,一對六或者一對一的比例。當我運行我的查詢時,我正在回收所有的用法。我只需要帶回最新的(SSUSED.usedate)。用於多個匹配的SQL邏輯
我也試圖過濾出某些產品和產品類別,似乎並不完全正常工作。我在這裏和那裏得到一個隨機產品,我似乎無法隔離該問題。我認爲這可能是因爲我的邏輯不是以一種乾淨有效的方式編寫的。
CODE:
SELECT DISTINCT
MEMBERS.scancode, MEMBERS.lname, MEMBERS.fname, MEMBERS.mtypeid, MEMBERS.status, MEMBERS.lastvisit, MEMBERS.datejoin,
PRODUCTS.description, EMPLOYEES.lname AS EmpLname, EMPLOYEES.fname AS EmpFName, SSUSED.transactiontype, SS.initialdate, SS.initialquantity,
SS.usedquantity, MEMBERTYPES.mtype, SS.ssid, SSUSED.usedate
FROM PRODUCTCATS INNER JOIN
PRODUCTS ON PRODUCTCATS.productcatid = PRODUCTS.productcatid INNER JOIN
SS ON PRODUCTS.productid = SS.productid INNER JOIN
MEMBERS ON SS.memid = MEMBERS.memid LEFT OUTER JOIN
SSUSED ON SS.ssid = SSUSED.ssid INNER JOIN
EMPLOYEES ON SSUSED.employeeid = EMPLOYEES.employeeid INNER JOIN
MEMBERTYPES ON MEMBERS.mtypeid = MEMBERTYPES.mtypeid
WHERE (SS.memid IN
(SELECT DISTINCT SS_1.memid
FROM SS AS SS_1 INNER JOIN
SSUSED AS SSUSED_1 ON SS_1.ssid = SSUSED_1.ssid INNER JOIN
MEMBERS AS MEMBERS_1 ON SS_1.memid = MEMBERS_1.memid
WHERE (MEMBERS_1.siteid = @rvSite) AND (SS_1.productid = '324' OR
SS_1.productid = '326') AND (SSUSED_1.usedate BETWEEN @rvStartDate AND @rvEndDate) AND (SSUSED_1.transactiontype = 'Use'))) AND
(PRODUCTS.productcatid = '27' OR
PRODUCTS.productcatid = '28' OR
PRODUCTS.productcatid = '29' OR
PRODUCTS.productcatid = '58' OR
PRODUCTS.productcatid = '77' OR
PRODUCTS.productcatid = '75' OR
PRODUCTS.productcatid = '30' OR
PRODUCTS.productcatid = '61' OR
PRODUCTS.productcatid = '31' OR
PRODUCTS.productcatid = '32' OR
PRODUCTS.productcatid = '47' OR
PRODUCTS.productcatid = '68') AND (SS.productid <> '32' OR
SS.productid <> '335' OR
SS.productid <> '350' OR
SS.productid <> '618' OR
SS.productid <> '1312' OR
SS.productid <> '1646' OR
SS.productid <> '54987' OR
SS.productid <> '55937' OR
SS.productid <> '58289' OR
SS.productid <> '58876' OR
SS.productid <> '601691') AND (SSUSED.transactiontype = 'Use' OR
SSUSED.transactiontype = 'Expired') AND (SSUSED.usedate >= @rvStartDate)
這是不是完全清楚這是試圖在這裏做什麼,但也許是TOP 1命令通過SSUSED.usedate DESC?或者,也許你可以用戶ROW_NUMBER?我強烈建議你在查詢中開始使用別名。它使它們更容易維護。 –
你只需要將所有這些OR改爲IN(value1,value2,value3 ..) – sagi
@sagi我打算說同樣的事情。考慮以下內容:'(PRODUCTS.productcatid IN('27','28 '','29','58','77','75','30','61','31','32','47','68'))AND(SS.productid NOT IN ('32','335','350','618','1312','1646','54987','55937','58289','58876','601691'))' – Leptonator