得到两张桌子的MIN

时间:2012-05-22 07:28:05

标签: mysql sql

我正在尝试从两个表中获取MIN值(一个返回值)。

以下mysql结构+数据:

table_master

`ID` (Unique) | `Amount`

1 | 5.8
2 | 22.1
3 | 44.22

table_variants

`table_master_ID` | `Amount`

1 | 4.11
1 | 5.12
1 | 
1 |
2 | 9.22
3 | 

使用此查询:

SELECT table_master.Amount, table_variants.Amount 
FROM table_master 
LEFT JOIN table_variants ON table_master.ID = table_variants.table_master_ID 
WHERE table_master.ID = 1

我得到这样的东西:

5.8 | 4.11
5.8 | 
5.8 | 5.12
...

现在我需要两个表的MIN Amount值。 ID的{​​{1}}是唯一的,table_master中的数据是可选的。

我该怎么做?我正在尝试使用table_variants MIN(),但没有成功。

任何提示?

TIA!

4 个答案:

答案 0 :(得分:3)

SELECT MIN(t.Amount) FROM
(SELECT Amount FROM table_master WHERE ID = 1
 UNION SELECT Amount FROM table_variants WHERE table_master_ID = 1) AS t

MySQL UNION Syntax

SELECT MIN(LEAST(table_master.Amount, table_variants.Amount))
FROM table_master 
LEFT JOIN table_variants ON table_master.ID = table_variants.table_master_ID 
WHERE table_master.ID = 1

MySQL LEAST Function

答案 1 :(得分:1)

尝试

SELECT MIN( CASE WHEN table_master.Amount<= table_variants.Amount AND table_variants.Amount IS NULL THEN table_master.Amount ELSE table_variants.Amount END) 
FROM table_master 
LEFT JOIN table_variants ON table_master.ID = table_variants.table_master_ID 
WHERE table_master.ID = 1

This shows how it works

答案 2 :(得分:0)

您可以使用UNION实现此目的:

SELECT  "min from table1", MIN( Amount ) FROM table_master
UNION 
SELECT  "min from table2", MIN( Amount ) FROM table_variants

答案 3 :(得分:0)

试试这个 -

SELECT LEAST(MIN(a.amount), MIN(b.value)) 
FROM table_master a, table_variants b
WHERE a.id = b.table_master_ID
AND a.id = 1;