MySQL:将搜索结果用作另一个搜索的输入

时间:2019-03-07 14:17:38

标签: mysql

您能否提供一些有关如何将搜索结果用于另一个搜索的建议?!

我有一个像
这样的桌子 表1

id | Country | City   | Amount 
---+---------+--------+------- 
 1 | US      | Dallas |     15 
 2 | US      | Dallas |     30 
 3 | US      | NY     |      7 
 4 | US      | Dallas |     11 
 5 | US      | NY     |     30 
 6 | US      | NY     |      1 

我需要按国家,城市分类数据,并找到第一个和最后一个值:
表2

Country / City / first / last
--------------------------
US / NY / 7 / 1
US / Dallas / 15 / 11

我可以按国家和城市分组,但如何使用:

select * from table1 group by country, city

我知道城市时可以找到第一个和最后一个值:

select * from table1 where city='NY' order by ID limit 1;
select * from table1 where city='NY' order by ID DESC limit 1;

但是我如何使用值(NY和Dallas)作为搜索输入,并且只有一个mysql查询?! :(

1 个答案:

答案 0 :(得分:0)

尝试一下:

with cte0 as 
(
  select 
    min(id) min_id, 
    max(id) max_id 
  from x
  group by Country, City
)
select 
  x.Country,
  x.City,
  min(x.Amount) Last,
  max(x.Amount) First
from x
where x.id in (select min_id from cte0 union select max_id from cte0)
group by Country, City