我已经问过(并解决了)一些接近的事情 here 但现在更复杂了。我有相同的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
谢谢!
答案 0 :(得分: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;
| 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 |
答案 1 :(得分: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