2012-05-22 97 views
1

我試圖從兩個表中獲取最小值(一個返回值)。獲取兩個表中的最小值

下面的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值。 IDtable_master是唯一的,table_variants中的數據是可選的。

我該怎麼做?我試圖MIN()CASE()但沒有成功。

任何提示?

TIA!

+0

沒有ü嘗試使用'min'在SELECT語句兩個結果.. ??? – Addicted

回答

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

+0

我需要編輯MYSQL UNION語法,但它的工作原理! – frgtv10

+0

金額必須是CAST(AMOUNT as UNSIGNED)'WHERE必須是這樣的'AND Amount!=''' – frgtv10

+0

CAST(AMOUNT as UNSIGNED)可能是錯誤的計算方式,可能會導致錯誤,因爲它忽略非整數數字的一部分。沒有它會得到什麼結果? – Ruben

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

0

您可以使用UNION到chieve這樣的:

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

你忘記了他要求ID = 1的那個 –

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;