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

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

Id_auction       bidder        item      bidder_number
1                Alice         cup            1
1                Ben           cup            2
2                Alice         mug            2
3                Ben           pen            1
3                Charles       pen            2

谢谢!

4

1 回答 1

2

试试这个:

SELECT *
FROM
(
  SELECT 
    t1.id_auction,
    t2.bidder_1 AS bidder,
    t2.item
  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
  FROM table1 t1
  INNER JOIN table1 t2  ON t1.id_auction = t2.id_auction
                       AND t2.winner_2 = 1
) AS sub
ORDER BY id_auction;

SQL 小提琴演示

这会给你:

| ID_AUCTION |  BIDDER | ITEM |
-------------------------------
|          1 |   Alice |  cup |
|          1 |     Ben |  cup |
|          2 |   Alice |  mug |
|          3 | Charles |  pen |
|          3 |     Ben |  pen |

更新 1

只需在第一个查询中选择一个bidder_number值为 1 的新列,在第二个查询中选择一个值为 2 的新列,如下所示:

SELECT *
FROM
(
  SELECT 
    t1.id_auction,
    t2.bidder_1 AS bidder,
    t2.item,
    1 AS bidder_number        -- <---------- This is the new column
  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                         -- < --------- with value 2 for bidders 2
  FROM table1 t1
  INNER JOIN table1 t2  ON t1.id_auction = t2.id_auction
                       AND t2.winner_2 = 1
) AS sub
ORDER BY id_auction, bidder;

这会给你:

| ID_AUCTION |  BIDDER | ITEM | BIDDER_NUMBER |
-----------------------------------------------
|          1 |   Alice |  cup |             1 |
|          1 |     Ben |  cup |             2 |
|          2 |   Alice |  mug |             2 |
|          3 |     Ben |  pen |             1 |
|          3 | Charles |  pen |             2 |

SQL 小提琴演示

于 2013-02-14T13:01:19.133 回答