1

我正在尝试从两个表中获取 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
...

现在我需要两个表的 MINAmount值。 IDoftable_master是唯一的,数据输入table_variants是可选的。

我怎样才能做到这一点?我正在尝试MIN()CASE()没有成功。

有什么提示吗?

蒂亚!

4

4 回答 4

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 语法

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 最小函数

于 2012-05-22T07:32:16.323 回答
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

这显示了它是如何工作的

于 2012-05-22T07:33:39.290 回答
0

您可以使用 UNION 来实现这一点:

SELECT  "min from table1", MIN( Amount ) FROM table_master
UNION 
SELECT  "min from table2", MIN( Amount ) FROM table_variants
于 2012-05-22T07:34:24.997 回答
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;
于 2012-05-22T07:36:07.307 回答