在mysql中使用嵌套查询选择查询

时间:2018-08-07 10:17:54

标签: mysql

我有2个表格(例如客户和详细信息),其中包含以下数据。我需要打印投资额最大的人员的详细信息。

客户:

+------+------------+--------+
| name | visited    | amount |
+------+------------+--------+
| xyz  | 2018-04-11 |    100 |
| xyz  | 2018-04-11 |   1000 |
| abc  | 2018-02-21 |    500 |
| xyz  | 2018-03-11 |    700 |
| abc  | 2018-01-24 |     50 |
+------+------------+--------+

详细信息:

+------+------------+
| name | detail     |
+------+------------+
| abc  | california |
| xyz  | hongkong   |
+------+------------+

我通过查询找到了投资最大金额的客户

select name,sum(amount) 
from (
  select name,amount 
  from customer 
  where visited >= DATE_SUB(CURDATE(),INTERVAL 8 MONTH)
) as subtable 
group by name 
order by amount 
limit 1;

我有以下输出

+------+-------------+
| name | sum(amount) |
+------+-------------+
| xyz  |        1800 |
+------+-------------+

现在如何从详细信息表中找到xyz的详细信息?我需要在单个查询中完成所有这些操作。我的输出必须像。

+------+------------+
| name | detail     |
+------+------------+
| xyz  | hongkong   |
+------+------------+

我被卡住了,该如何进行?

3 个答案:

答案 0 :(得分:0)

select d.name, d.details, sum(c.amount) 
from details d
join customer c on c.name = d.name
where c.visited >= DATE_SUB(CURDATE(),INTERVAL 8 MONTH)
group by d.name 
order by sum(c.amount) desc
limit 1

答案 1 :(得分:0)

您需要JOIN进入详细信息表。我决定使用子查询来限制要为联接操作查找的行数。

select c.name, d.detail
from (
  select 
    name,
    sum(amount) as sum_amount
  from customer
  where visited >= DATE_SUB(CURDATE(),INTERVAL 8 MONTH)
  group by name
  order by sum_amount
  limit 1
) c
left join details d on c.name = d.name

请注意,我已删除了您的子查询,因为它是多余的。

答案 2 :(得分:0)

要获得以下输出,可以使用join编写查询,如下所示:

输出:-

buffer

查询:-

lpNumberOfBytesRead

如果要打印总金额,则只需在select语句中再添加一列:

输出:-

    +------+------------+
    | name | detail     |
    +------+------------+
    | xyz  | hongkong   |
    +------+------------+

查询:-

select d.name, d.details
from details d
join customer cust on cust.name = d.name and
    cust.visited >= DATE_SUB(CURDATE(),INTERVAL 8 MONTH)
group by d.name 
order by sum(cust.amount) desc
limit 1;