我有3个表table_1,table_2和table_3具有公共列comm_name作为外键。我只想通过连接这3个表来查找列data_id的最大值。使用where comm_name
简而言之:联合这三个表并找到最大数据_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)
答案 0 :(得分:3)
Union运算符应该帮助您拥有一个可以查询(未测试)的数据集:
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)
答案 1 :(得分: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
);