我有一张桌子: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
谢谢!
答案 0 :(得分: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;
这会给你:
| ID_AUCTION | BIDDER | ITEM |
-------------------------------
| 1 | Alice | cup |
| 1 | Ben | cup |
| 2 | Alice | mug |
| 3 | Charles | pen |
| 3 | Ben | pen |
只需在第一个查询中选择值为1的新列bidder_number
,在第二个查询中选择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 |