我有问题。在我的表Wallets
中,我有5种硬币:LTC,BTC,ETH,BNB和USDT。现在,我首先要选择具有最高价值的硬币,而不是USDT。第二枚硬币必须是USDT硬币。所以我尝试了这个查询:
SELECT *
FROM Wallets
WHERE NOT Coin='USDT'
ORDER BY Value DESC LIMIT 1
UNION
SELECT *
FROM Wallets
WHERE Coin='USDT'
但是,这给了我除USDT之外的所有硬币...奇怪的是,当我分别运行两个查询时,结果是正确的。我在做什么错了?
以下是我的表格布局示例:
+------+----------+-------+
| Coin | Quantity | Value |
+------+----------+-------+
| LTC | 10 | 200 |
| BTC | 2 | 12000 |
| BNB | 0 | 2 |
| ETH | 0 | 0.1 |
| USDT | 0 | 0 |
+------+----------+-------+
现在我想要这个结果:
+------+----------+-------+
| Coin | Quantity | Value |
+------+----------+-------+
| BTC | 2 | 12000 |
| USDT | 0 | 0 |
+------+----------+-------+
答案 0 :(得分:1)
使用UNION ALL
代替UNION
(SELECT * FROM Wallets WHERE NOT Coin='USDT' ORDER BY Value DESC LIMIT 1)
UNION ALL
SELECT * FROM Wallets WHERE Coin='USDT'
编辑:仅适用于MySQL 8
答案 1 :(得分:0)
查询的问题是缺少括号。因此,这应该可行:
(SELECT w.*
FROM Wallets w
WHERE Coin <> 'USDT'
ORDER BY Value DESC
LIMIT 1
) UNION
(SELECT w.*
FROM Wallets w
WHERE Coin = 'USDT'
);
我建议使用UNION ALL
,但这并不重要,因为没有重复-COIN
列(至少)是不同的。
实际上,这将按顺序返回结果。但是,MySQL不保证UNION ALL
的结果是正确的(据我所知),因此我认为您应该添加一个额外的ORDER BY
:
(SELECT w.*
FROM Wallets w
WHERE Coin <> 'USDT'
ORDER BY Value DESC
LIMIT 1
) UNION ALL
(SELECT w.*
FROM Wallets w
WHERE Coin = 'USDT'
)
ORDER BY (Coin <> 'USDT') DESC;