MYSQL:从两个不同的表中选择VARCHAR字段中的最大值

时间:2016-07-15 10:38:19

标签: mysql sql

我是MYSQL的新手。有两个表,即表A和表B.只需要两个不同表中的Max值。
预期输出:

AG/2016-17/P/046


  table_A                                 
       In_No
     AG/2016-17/P/01
     AG/2016-17/P/029
     AG/2016-17/P/030

     table_B
      In_No
 AG/2016-17/P/01
 AG/2016-17/P/046
 AG/2016-17/P/015

SQL:

select MAX(bv) from(
SELECT MAX(CAST(SUBSTRING(In_No, 14, length(In_No)-3) bv AS UNSIGNED)) FROM table_A
union all
SELECT MAX(CAST(SUBSTRING(In_No, 14, length(In_No)-3) bv AS UNSIGNED)) FROM table_B) as a

出了点问题。它没有显示正确的输出。请建议我。谢谢。

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT In_No, substring_index(In_No, '/', 2) AS In_No_sub
FROM (
    SELECT In_No FROM table_A
    UNION ALL
    SELECT In_No FROM table_B
) t
ORDER BY substring_index(In_No, '/', -1) + 0 DESC
LIMIT 1

SQLFiddle Demo

答案 1 :(得分:0)

试试这个

select MAX(bv) 
from(
    SELECT MAX(CAST(SUBSTRING(In_No, 14, length(In_No)) as UNSIGNED INTEGER)) as bv FROM table_A
    union all
    SELECT MAX(CAST(SUBSTRING(In_No, 14, length(In_No)) as UNSIGNED INTEGER)) as bv FROM table_B
)  as a