[英]MySQL Join two tables with condition
基于这两个表:
products
| ID | Active | Name | No
--------------------------------------------------
| 1 | 1 | Shirt | 100
| 2 | 0 | Pullover | 200
variants
| MasterID | Active | Name | No
--------------------------------------------------
| 1 | 1 | Red | 101
| 1 | 0 | Yellow | 102
我想在一个sql中获得所有处于活动状态的产品以及它们的活动变体。 这些表之间的关系MasterID
> ID
所需结果:
ID (master) | Name | No
--------------------------------------------------
1 | Shirt | 100
1 | Red | 101
我尝试使用union进行尝试,但随后无法获得所属的MasterID。
这应该给您预期的结果:
select * from products left join variants on products.id = variants.masterId
where products.active=1 and variants.active=1
如果不是,请将预期结果添加到您的问题中。
看来您只需要一个简单的连接:
select * from products left join variants on products.ID = variants.MasterID where products.Active = 1 and variants.Active = 1
要求更加明确之后的更新 :
select ID, Name, No, 'products' as RowType from products where Active = 1 union select variants.MasterID as ID, variants.Name, variants.No, 'variants' as RowType from products join variants on products.ID = variants.MasterID where products.Active = 1 and variants.Active = 1 order by ID, RowType, No
我假设您希望结果按ID排序, products
后跟variants
。 No列可能以这种方式隐式排序(没有实际数据是不可能知道的),在这种情况下,可以删除RowType
列。 可能需要更改order by
子句以匹配您的特定RDBMS。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.