簡體   English   中英

MySQL:從左連接中選擇一行,結果只有多行

[英]MySQL: Select one row from left join only once in result wth multiple rows

好吧,在SO的幫助和一些我自己公認的有限腦力的幫助下,我的查詢大部分都在起作用。 我從LEFT JOIN得到了我想要的結果,它出現在外部查詢中。 但是,對於具有相同ID的每一行,它會顯示多次,這是預期的,但這不是我需要的......

我想知道是否有可能只顯示一次加入的結果。 我在網上找到了很多答案,只是從已加入的表中拉出第一行。 但是,我正在尋找的只是在結果中顯示一次連接結果 (不一定是第一次)。

這是我查詢的[簡化版]:

select
    `order`.order_id,
    `order`.total,
    `order`.comment,
    `order`.shipping_cost,
    `ct`.amount as credit
from `order`
left join (
    select
        customer_id,
        sum(amount) as amount
    from `customer_transaction`
    where
        amount > 0
        and integrated = 0
    group by
        customer_id
) as ct
    on `ct`.`customer_id` = `order`.`customer_id`
where
    `order`.integrated = 0;

這應該做的是獲得尚未整合的訂單信息,同時包括客戶信用。 不幸的是,信用卡存儲在ct表中的行中,而不是與特定訂單相關聯,這是有道理的,但是集成它的軟件希望這個號碼在訂單上。

上述查詢“有效”,直到一個客戶有多個訂單。 在這種情況下,如果我使用上述查詢,它將有效地認為所有訂單都已應用信用。 例如,上面的查詢返回如下結果:

+-------------+----------+-----------+---------+---------------+--------+
| customer_id | order_id | total     | comment | shipping_cost | credit |
+-------------+----------+-----------+---------+---------------+--------+
|       52227 |   184589 |   28.6910 |         |       12.7410 | 8.0000 |
|       52227 |   184590 |   28.6910 |         |       12.7410 | 8.0000 |
+-------------+----------+-----------+---------+---------------+--------+

該客戶的“賬戶”信用額度為8美元,而不是16美元。 即,客戶的未使用信用交易總和加起來為8.我試圖獲得該信用僅出現一次。 換句話說,這是我想要的結果:

+-------------+----------+-----------+---------+---------------+--------+
| customer_id | order_id | total     | comment | shipping_cost | credit |
+-------------+----------+-----------+---------+---------------+--------+
|       52227 |   184589 |   28.6910 |         |       12.7410 | 8.0000 |
|       52227 |   184590 |   28.6910 |         |       12.7410 | NULL   |
+-------------+----------+-----------+---------+---------------+--------+

(注意右下角的NULL。它也可能是0,甚至可能是8 / $ NUM_ROWS。我必須檢查軟件是否可以使用它。可能不會。)

這種瘋狂的原因是因為一個軟件將信用存儲為與客戶相關聯的一行或多行,而另一個軟件將其視為一個訂單的一部分,並且它應該全部“同時”集成。 它運行一個查詢以獲取所有訂單信息,包括信用,第二個用於訂單項(無信用)。 所以...我需要將訂單信用,然后將其設置為integrated = 1,以便下次不會使用它(我已經有了這部分工作)。

任何想法如何我只能顯示一次信用,或者這是不是可以用“簡單”查詢(而不是代碼)?

謝謝

您可以使用左連接執行此操作。 我們的想法是在left join的第一個表中有一個序列號:

select o.order_id, o.total, o.comment, o.shipping_cost, ct.amount as credit
from (select o.*,
             @rn :=  if(@cid = customer_id, @rn + 1, 1) as rn,
             @cid := customer_id
      from `order` o cross join
           (select @rn := 0, @cid := 0) vars
     ) o left join
     (select customer_id, sum(amount) as amount
      from `customer_transaction`
      where amount > 0 and integrated = 0
      group by customer_id
     ) ct
     on `ct`.`customer_id` = o.`customer_id` and o.rn = 1
where o.integrated = 0;

如果需要, left join將保留第一個表中的所有行以及第二個表中的匹配行。 因為條件o.rn = 1僅匹配第一行,所以只有第一行才能獲得值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM