简体   繁体   English

MySQL 5.5从table2中为表1中的每个唯一ID选择MAX

[英]MySQL 5.5 select MAX from table2 for every unique id in table1

I have two tables: 我有两个表:

table1        table2
column id     column id   column value
1             1           count_20
2             1           count_30
3             2           count_20
4             2           count_50
...           2           count_200
              3           count_30
              3           count_50
              3           count_200
              4           count_130
              ...         ...

I want to build a query that will select every row from table1, column id and the MAX value from the corresponding column value from table2 and make a DESC short as int in value column. 我想构建一个查询,该查询将从table1, column id每一行table1, column id以及从table2的相应column value选择MAX值,并将DESC缩写为int in value column。

So the output should be: 因此输出应为:

table1.id     value
2             count_200  
3             count_200  
4             count_130  
1             count_30  
...           ...  

I have tried JOIN but then, for every value (count_%) in table2 I get the corresponding id from table1 . 我尝试了JOIN但是随后,对于table2每个value (count_%) ,我都从table1获得了相应的id

SELECT table1.id, table2.id, table2.value FROM table1
LEFT JOIN table2
ON table2.id=table1.id
WHERE table1.id<'100'
ORDER BY
CASE value
  WHEN 'count_20' THEN '20' 
END DESC,
CASE value
  WHEN 'count_30' THEN '30' 
END DESC,
CASE value
  WHEN 'count_50' THEN '50' 
END DESC,
CASE value
  WHEN 'count_130' THEN '130' 
END DESC,
CASE value
  WHEN 'count_200' THEN '200' 
END DESC;

Output: 输出:

table1.id   table2.id   value
2           2           count_200  
3           3           count_200  
4           4           count_130  
2           2           count_50  
3           3           count_50  
1           1           count_30  
3           3           count_30  
1           1           count_20  
2           2           count_20  
...         ...  

Any help would be appreciated. 任何帮助,将不胜感激。

Give this a try: 试试看:

select t2.id, 
'count_' + cast(max(cast(replace(t2.value, 'count_', '') as int)) varchar) intValue
from table1 t1
join table2 t2 on t1.id = t2.id
group by t2.id
order by max(cast(replace(t2.value, 'count_', '') as int)) desc

This results in: 结果是:

+----+-----------+
| ID |   VALUE   |
+----+-----------+
|  2 | count_200 |
|  3 | count_200 |
|  4 | count_130 |
|  1 | count_30  |
+----+-----------+

Fiddle here . 在这里摆弄。

http://www.w3schools.com/sql/sql_distinct.asp check this out. http://www.w3schools.com/sql/sql_distinct.asp进行检查。 this will only show the values onces. 这只会显示一次值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM