I have 2 Tables (The relevant ones for this question). One for Customers, second for loans.
What I am trying to accomplish is to get each customer's information, and in addition to that how many loans he toked.
我的用户表
+--------+-------+-------+-----+
| cst_id | fname | lname | age |
+--------+-------+-------+-----+
| 1 | xx | yy | 11 |
| 2 | xx | yy | 22 |
| 3 | xx | yy | 33 |
| 4 | xx | yy | 44 |
| 5 | xx | yy | 55 |
+--------+-------+-------+-----+
贷款表
+---------+-----------------+
| cust_id | loan_variant_id |
+---------+-----------------+
| 1 | 1 |
| 1 | 2 |
| 2 | 3 |
| 2 | 1 |
| 3 | 1 |
+---------+-----------------+
We see that customers with ID 1 have 2 registered loans.
最后一张桌子应该是什么样子
您可以忽略新列"name",因为它与问题无关.
+--------+-------+-------+-----+-------+------------+
| cst_id | fname | lname | age | name | loan_count |
+--------+-------+-------+-----+-------+------------+
| 1 | xx | yy | 11 | xx yy | 2 |
| 2 | xx | yy | 22 | xx yy | 2 |
| 3 | xx | yy | 33 | xx yy | 1 |
| 4 | xx | yy | 44 | xx yy | 0 |
| 5 | xx | yy | 55 | xx yy | 0 |
+--------+-------+-------+-----+-------+------------+
我的SQL代码
SELECT
*,
CONCAT(fname, ' ', lname) AS name,
COUNT(##some magic code please, at least what i think##) AS loan_count
FROM
t_cst
现在我知道,通过这个查询,我可以在t_loans表中完成我想要的(计算每个用户 token 的贷款数量).然而,我对如何同时使用这两个查询有点困惑.
SELECT
COUNT(cust_id) AS loansCountForEachCst
FROM
t_loans
GROUP BY
(cust_id)
有什么 idea 吗?