2016-07-23 42 views
3

我有3个表table_1,table_2和table_3具有公共列comm_name作为外键。我只想通过连接这3个表来找到列的最大值data_id。使用Where条件comm_name连接表并查找列值的最大值

总之:联盟这三个表,找到最大data_id,即:回9

我想这样的:

SELECT max(data_id) FROM ((SELECT table_1.data_id FROM table_1 where comm_name='aa') UNION(SELECT table_2.data_id FROM table_2 where comm_name='aa') UNION(SELECT table_3.data_id FROM table_2 where comm_name='aa')); 

但其示值误差

An expression was expected. (near "(" at position 26) 
Unexpected token. (near "(" at position 26) 
Unexpected token. (near "(" at position 27) 
This type of clause was previously parsed. (near "SELECT" at position 29) 
This type of clause was previously parsed. (near "SELECT" at position 125) 
This type of clause was previously parsed. (near "SELECT" at position 220) 

enter image description here

回答

3

联盟运营商应该帮助你有1个数据集,您可以查询(未测试):

select max(data_id) from (select data_id from table_1 union select data_id from table_2 union select data_id from table_3) 
0

尝试这个

SELECT Name, MAX(data_id) as MaxId 
    FROM 
    (
     SELECT data_id 
     FROM table1 
     UNION ALL 
     SELECT data_id 
     FROM table2 
     UNION ALL 
     SELECT data_id 
     FROM table3 
    ); 
+0

如何添加where条件检查comm_name是相同的三个表 –