mysql - 两个不同列的sql语句

标签 mysql sql

我正在尝试在两列之间进行 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

表_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 匹配的值,这些值是在 table_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"

关于mysql - 两个不同列的sql语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30932361/

相关文章:

php - MySQL:使用 REGEX 从一条记录中提取所有匹配项

php - 我如何在 django 中使用现有数据库(mysql)?

mysql - 如何创建此查询?

SQL:以文本形式显示描述而不是位值

Sql查询从表Employee中获取全名消除空值

MySQL事务和触发器

python - 使用 for 循环在 django 模板中显示值

python - MySQLdb fetcall,AttributeError : 'int' object has no attribute 'fetchall'

sql - 在 SQL Server 中使用 DATEPART 时出现错误的周数

sql - 针对哈希 token 的 SQL SELECT 定时攻击的对策