【问题标题】:SQL Outer Join FunctionSQL 外连接函数
【发布时间】:2009-03-16 20:21:45
【问题描述】:

我以前写过这个函数,但我好像不记得了,它也没有进入版本控制。现在,更多的是与睡眠剥夺有关,我不记得如何重建它。

这就是想法。我有两个表,“regPrice”和“custPrice”,共享密钥“itemID”。它们都有一个“价格”列,并且 custPrice 也有另一个键“acct”,因此如果 custPrice 中存在价格,它应该返回那个。如果没有 custPrice 条目,它应该返回 regPrice。

伪代码:

if(select custPrice where acct = passedAcct and itemID = passedItemID) {
   return custPrice;
else 
   return regPrice;

任何帮助将不胜感激。

【问题讨论】:

    标签: sql mysql stored-procedures join


    【解决方案1】:
    SELECT COALESCE(c.price, r.price) AS price
    FROM regPrice r LEFT OUTER JOIN custPrice c
     ON (r.itemID = c.itemID AND c.acct = ?)
    WHERE r.itemID = ?;
    

    【讨论】:

    • 看起来不错。要使其成为存储过程,只需: CREATE PROCEDURE 定价 (I_itemID INT, I_acct INT) SELECT COALESCE(c.price, r.price) AS price FROM regPrice r LEFT OUTER JOIN custPrice c ON (r.itemID = c. itemID AND c.acct = I_acct) 其中 r.itemID = I_itemID;这是正确的吗?
    【解决方案2】:
    select r.itemID, r.Acct,
    case when c.price is null then r.price else c.price end as price
    from regPrice r
    left outer join custPrice c
    on r.itemID = c.itemID
    and r.Acct = @passedAcct
    where r.itemID = @passedItemID
    

    【讨论】:

    • CASE 或 COALESCE 之间是否存在性能差异?
    【解决方案3】:

    查看 COALESCE 函数,除非您不使用 NULL,在这种情况下您将需要使用 CASE。

    【讨论】:

    • 听起来像 sql server - 他要求 mysql
    猜你喜欢
    • 2012-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 2021-01-31
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多