1
比方說,我有一個產品的成本很少變動商店,所以我成立了一個成本表看起來是這樣的:SQlite的:保存/註冊子查詢重複使用的
CREATE TABLE costs VALUES (
itemid INTEGER
cost DOUBLE
date DATETIME
FOREIGN KEY(itemid) REFERENCES items(itemid)
);
如果我想當前成本的輸出,當最後更新,我可以這樣做:
SELECT items.name, cost, latestdate
FROM items
LEFT NATURAL JOIN (
SELECT itemid, costs.cost, latestdate
FROM (
SELECT itemid, MAX(date) as latestdate
FROM costs
GROUP BY itemid
)
LEFT NATURAL JOIN costs
WHERE date = latestdate
);
是否有可能保存子查詢,以便該查詢可以寫成這樣:
SELECT items.name, cost, latestdate
FROM items
LEFT NATURAL JOIN get_current_cost();
或者,在 「成本 - 前 - 日期」 的局面:
SELECT items.name, cost
FROM items
LEFT NATURAL JOIN (
SELECT itemid, costs.cost, latestdate
FROM (
SELECT itemid, MAX(date) as latestdate
FROM costs
GROUP BY itemid
WHERE date < *somedate*
)
LEFT NATURAL JOIN costs
WHERE date = latestdate
);
-- Change To
SELECT items.name, cost
FROM items
LEFT NATURAL JOIN get_cost_by(*somedate*)
謝謝!找出合適的搜索條件始終是最難的部分: - / –