user001
user001

Reputation: 991

How to Select max Value from 2 tables in MySQL

I have 2 tables in MySQL DB.

Both the tables have a column as ID which is of type int(10) unsigned.

Table1 has no data and Table2 has the ID as 24.

I am using the below query to get the max ID

select max(ID) from 
(        
   select IFNULL(max(ID),0) as ID from table1 
   UNION 
   select IFNULL(max(ID),0) as ID from table2
)temp;

I am expecting the value 24 but it gives 0.

Anything wrong in my query? Please help.

Upvotes: 0

Views: 1764

Answers (1)

John Woo
John Woo

Reputation: 263943

try this,

SELECT IFNULL(MAX(ID), 0) ID
FROM
(
    SELECT ID FROM table1
    UNION ALL
    SELECT ID FROM table2
) a

Upvotes: 3

Related Questions