简体   繁体   中英

sql statement for two different columns

I am trying to make sql query between two columns.

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

By using query below I get as a result only list of products that are selected in table_2. That is good I need to get that, but I also want to print all values from table_1 in same query for later programming I need that. Not sure is it possible to make one column that will print 1 if product_ID and ID match and if not print 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"

I want to print values from table_1 match with table_2 what are selected in table_2. I am getting stuck here any advice is appreciated.

As i am right with your requirenments this untested query should work:

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

Try this

$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 like this since the connection between table 1 and table 2 is the ID and the product.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM