![](/img/trans.png)
[英]SQL - merge two queries with different number of columns in select statement into one
[英]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.