再一次,任何Mysql专家都可以帮我解决Mysql语句吗? 我有:2个表与外键userid和balanceID
连接我需要什么:我需要找行哪里是MAX值我们说债务和MIN值贷款,我对此声明的期望是找到最高价值债务和最低贷款(1行)例如:在这种情况下,它将是行名称2 | 200 |这可能吗?做过研究,无法找到解决方案,任何帮助表示赞赏。
答案 0 :(得分:1)
根据您的最小数据集进行猜测,但可能类似于:
select top 1 balanceID, balance, debt, loan
from Balance
order by debt - loan desc
如果您想按UserID
分组,例如:
select b.balanceID, b.balance, b.debt, b.loan
from Balance b
inner join (
select UserID, max(debt - loan) as MaxDebt
from Balance
group by UserID
) bm on b.UserID = bm.UserID and (b.debt - b.loan) = MaxDebt
答案 1 :(得分:0)
您可以JOIN
只使用第二个表中的最小贷款和最大余额的两个表,如下所示:
SELECT u.name, t.balance, t.loan
FROM users u
INNER JOIN
(
SELECT *
FROM table2
WHERE balance = (SELECT MAX(balance) FROM table2)
AND debt = (SELECT MIN(loan) FROM table2)
) t ON -- JOIN condition