1

我已经在这里问过(并解决了)一些问题 但现在更复杂了。我有相同的 BID 表:

Id_auction        bidder_1      winner_1    bidder_2    winner_2    item
  1                Alice           1          Ben         1          cup
  2               Charles          0          Alice       1          mug
  3                 Ben            1          Charles     1          pen

但现在我想将信息与另一张表 USD

Id_auction         USD
1                  100
2                  150
3                   50

如果投标人是赢家,则值为 1,如果不是赢家,则值为 0。因此,在第一次拍卖中,Alice 和 Ben 是赢家,在第二次拍卖中只有 Alice 获胜。我将需要一个 MySQL 查询,因此结果将如下所示:

  Id_auction       bidder        item      bidder_number   USD
  1                Alice         cup            1          100
  1                Ben           cup            2          100
  2                Alice         mug            2          150
  3                Ben           pen            1           50
  3                Charles       pen            2           50

谢谢!

4

2 回答 2

4

只需JOIN这张桌子USD

SELECT sub.*, USD.USD
FROM
(
  SELECT 
    t1.id_auction,
    t2.bidder_1 AS bidder,
    t2.item,
    1 AS bidder_number    
  FROM table1 t1
  INNER JOIN table1 t2  ON t1.id_auction = t2.id_auction
                       AND t2.winner_1 = 1
  UNION ALL
  SELECT 
    t1.id_auction,
    t2.bidder_2 AS bidder,
    t2.item,
    2                    
  FROM table1 t1
  INNER JOIN table1 t2  ON t1.id_auction = t2.id_auction
                       AND t2.winner_2 = 1
) AS sub
INNER JOIN USD ON sub.id_auction = USD.id_auction
ORDER BY id_auction, bidder;

更新的 SQL Fiddle 演示

| ID_AUCTION |  BIDDER | ITEM | BIDDER_NUMBER | USD |
-----------------------------------------------------
|          1 |   Alice |  cup |             1 | 100 |
|          1 |     Ben |  cup |             2 | 100 |
|          2 |   Alice |  mug |             2 | 150 |
|          3 |     Ben |  pen |             1 |  50 |
|          3 | Charles |  pen |             2 |  50 |
于 2013-03-28T11:41:46.977 回答
1
SELECT
  BID.Id_auction AS Id_auction,
  BID.bidder_1 AS bidder,
  BID.item AS item,
  USD.USD AS USD,
  1 AS bidder_number
FROM BID
INNER JOIN USD ON BID.Id_auction=USD.Id_auction
WHERE BID.winner_1=1

UNION ALL

SELECT
  BID.Id_auction AS Id_auction,
  BID.bidder_2 AS bidder,
  BID.item AS item,
  USD.USD AS USD,
  2 AS bidder_number
FROM BID
INNER JOIN USD ON BID.Id_auction=USD.Id_auction
WHERE BID.winner_2=1

ORDER BY BID.Id_auction, budder_number
于 2013-03-28T11:44:10.737 回答