[英]How to join 2 tables with getting all rows from left table and only matching ones in right
表格1
表 2
Table2.plan_selected 顯示了用戶選擇的計划。
例如:表 2 中 user_id=4 的用戶從表 1 中選擇 id = 2 計划。
我想從 Table1 中獲取所有行,並且只從 Table2 中獲取特定user_id
的匹配行。
預期的結果是這樣的。
我想獲取 Table1 的所有行,並且只從 Table2 中獲取特定 user_id 的選定計划,比如 4。
預期的結果將是這樣的:
id name plan type plandetails requestper month price is deleted 計划選擇
1 每月執行 {1000 次請求} 1000 50 0 NULL
2 基本月度 {500 MAY REQUSTS} 1000 25 0 2
3 FREEEE MONTHLY {10 MAY REQUSTS} 1000 0 0 NULL
4 每年執行 {1000 次請求} 1000 500 0 NULL
5 基本年度 {500 可能要求} 1000 250 0 NULL
6 FREEEE 每年 {10 MAY REQUSTS} 1000 0 0 NULL
我嘗試做的是使用簡單的左連接。
select plans.id, name, plan_details, plan_type, request_per_month, price,is_deleted, plan_selected from SubscriptionsPlans as plans left join SubscriptionsOrder as orders on plans.id=orders.plan_selected where orders.user_id = 4
這是我的 2 個模型。 ORM 查詢集或 SQL 查詢會有所幫助
class SubscriptionsPlans(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=255)
plan_type = models.CharField(max_length=255)
plan_details = models.TextField(max_length=1000)
request_per_month = models.IntegerField()
price = models.FloatField()
is_deleted = models.BooleanField(default=False)
class SubscriptionsOrder(models.Model):
id = models.IntegerField(primary_key=True)
user_id = models.ForeignKey(
AppUser,
null=True,
on_delete=models.SET_NULL
)
plan_selected = models.ForeignKey(SubscriptionsPlans, null=True, on_delete=models.SET_NULL)
billing_info = models.IntegerField()
您可以查詢:
SubscriptionsPlans.objects.filter(subscriptionsorder__user_id=4)
這將列出具有4
作為user_id
的SubscriptionOrder
的所有SubscriptionPlans
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.