繁体   English   中英

如何通过从左表中获取所有行并仅在右表中匹配来连接 2 个表

[英]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_idSubscriptionOrder的所有SubscriptionPlans

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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