簡體   English   中英

兩個不同列的sql語句

[英]sql statement for two different columns

我正在嘗試在兩列之間進行sql查詢。

表格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的所有值,以便以后需要進行編程。 如果product_ID和ID匹配,則不確定是否可以使一列打印1;否則,打印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_1的值與table_2匹配的表_2中選擇的值。 我被困在這里,任何建議都值得贊賞。

由於我對您的要求正確,因此未經測試的查詢應該可以正常工作:

$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"

嘗試這個

$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"
$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"

Kinda之所以這樣,是因為表1和表2之間的連接是ID和產品。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM