2015-06-19 90 views
1

我想在兩列之間進行SQL查詢。SQL語句爲兩個不同的列

TABLE_1

ID  ProductName  ProductDescription 
1  Prod_1    Description_1 
2  Prod_2    Description_1 
3  Prod_3    Description_1 
4  Prod_4    Description_1 
5  Prod_5    Description_1 

TABLE_2

ID  Product  Partner 
1   1    21 
2   2    21 
3   3    21 
4   1    32   
5   1    32    
6   4    21    
7   5    21 
8   5    32 

通過使用下面的查詢,我得到的結果僅是在TABLE_2選擇的產品清單。這很好,我需要這樣做,但我也希望在同一個查詢中打印來自table_1的所有值,以便稍後進行編程。不知道是有可能使一列,將打印1,如果PRODUCT_ID和ID匹配,如果不打印0

$query = "SELECT a.ID, a.ProductName, b.ID, b.Product, b.Partner 
FROM table_1 a 
LEFT JOIN table_2 b 
ON a.ID = b.Product 
WHERE b.Partner = 21" 

我想打印在TABLE_2選擇什麼TABLE_2從TABLE_1匹配值。 我在這裏卡住任何意見表示讚賞。

+2

請發佈預期結果也 –

+0

我也陷在這裏了,但如果你也發佈了你的預期輸出,那就不會發生了。 –

+0

我認爲它應該是a.ID = b.Product。可能 –

回答

4

正如我與你requirenments是對的這個未經測試的查詢應該工作:

$query = "SELECT a.ID, a.ProductName, b.ID, b.Product, b.Partnerm, case when b.id is null then 0 else 1 end 
FROM table_1 a 
LEFT JOIN table_2 b 
ON a.ID = b.ID and b.Partner = 21" 
+0

@ user3651819對不起,忘記在案件前的逗號。已添加它。請再試一次。 – Jens

+0

非常感謝你 – user3651819

+0

@ user3651819不客氣 – Jens

1

試試這個

$query = "SELECT a.ID, a.ProductName, b.ID, b.Product, b.Partnerm case when b.id is null then 0 else 1 end 
    FROM table_1 a 
    LEFT JOIN table_2 b 
    ON a.ID = b.Product and b.Partner = 21" 
1
$query = "SELECT a.ID, a.ProductName, b.ID, b.Product, b.Partner FROM table_1 a LEFT JOIN table_2 b 
ON a.ID = b.Product WHERE b.Partner = 21" 

有點像這一點,因爲表1和表2之間的連接是ID和產品。

+0

這不是一個答案。它沒有給出正確的解決方案。但是你是對的我犯了錯誤,它應該是b.Partner,但仍然不正確 – user3651819

+0

現在我很困惑xD ...如果你想提供一個sqlfiddle,會更容易。 –

+0

@Jens給出了正確的解決方案。感謝您的幫助 – user3651819