gpt4 book ai didi

mysql - 从不同的列中选择数据

转载 作者:行者123 更新时间:2023-11-29 06:51:51 25 4
gpt4 key购买 nike

我有一个表: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

谢谢!

最佳答案

试试这个:

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 Fiddle Demo

这会给你:

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

更新1

只需在第一个查询中选择一个值为 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 |

SQL Fiddle Demo

关于mysql - 从不同的列中选择数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14875360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com