2017-05-10 81 views
0

使用這個問題在那裏與Get Last Row of Different id then display data that is greater than zero獲取最後一行或最小的數據,那麼在連接兩個表

我想加盟另一臺

這是我的表2

+----+--------+ 
| id | name | 
+----+--------+ 
| 1 | Taylor | 
| 2 | Zac | 
| 3 | Scott | 
| 4 | Emma | 
+----+--------+ 

如果我使用此代碼...

SELECT DISTINCT t1.id, t1.amount, t2.name FROM table1 t1, table2 t2 WHERE t1.amount = (SELECT MIN(t1.amount) FROM table1 WHERE id= t1.id) AND t1.[t1.amount]>0 AND t1.[id]=t2.[id]; 

...然後這些結果顯示...

+----+--------+-------+ 
| id | amount | name | 
+----+--------+-------+ 
| 2 | 100 | Zac | 
+----+--------+-------+ 

僅1數據顯示

我想是在表

+----+--------+-------+ 
| id | amount | name | 
+----+--------+-------+ 
| 2 | 100 | Zac | 
| 4 | 200 | Emma | 
+----+--------+-------+ 
+0

您是否試過將't1。[t1.amount]'改爲't1.amount'? – toonice

回答

0
SELECT DISTINCT t.id,t2.name,t.amount 
FROM table t 
INNER JOIN table2 t2 ON t.id=t2.id 
WHERE amount = (SELECT MIN(amount) FROM table WHERE id= t.id) 
and amount>0; 
+0

我嘗試使用我們的代碼,它仍然顯示1個數據 – elaine8s

+0

@ elaine8s這應該工作,我猜在第二個表中沒有匹配的ID。嘗試將'INNER JOIN'改爲'LEFT JOIN'並檢查。 –

+0

謝謝我試過左連接,它的工作原理。感謝你的幫助:) – elaine8s

0

相信你要找的第一個表的子查詢兩個數據,請嘗試以下操作:

SELECT DISTINCT t1.id, t1.amount, t2.name 
FROM (SELECT DISTINCT id, amount FROM table t 
WHERE amount = (SELECT MIN(amount) FROM table WHERE id= t.id) 
and amount>0) t1, table2 t2 
WHERE t1.[id]=t2.[id]; 

不確定爲什麼你當前的查詢不起作用,但希望這有助於!

+0

我試過使用我們的代碼,它仍然顯示1個數據 – elaine8s

+0

非常好奇,你可以確認查詢從https://stackoverflow.com/questions/43861893/get-last-row-of-different-id-then- display-data-that-is-greater-zero正在返回兩行? –

+0

是的,它有兩行。 – elaine8s

0

請嘗試以下...

SELECT table2.id AS id, 
     minAmount AS amount, 
     name 
FROM (SELECT id, 
       MIN(amount) AS minAmount 
     FROM table1 
     GROUP BY id 
     HAVING MIN(amount) > 0 
    ) AS table1Refiner 
INNER JOIN table2 ON table1Refiner.id = table2.id; 

此語句獲得結果,按您的第一個問題,並且基於id他們共同的價值觀他們加入到table2工作,有效地追加相應的nameidamount。然後選擇並輸出這些字段。

如果您有任何問題或意見,請隨時發佈相應評論。

+0

它在FROM子句中有一個錯誤 – elaine8s

+0

請指定錯誤。 – toonice

+0

發現錯誤 - 處理解決方案。 – toonice

相關問題