使用相同的列连接两个表

时间:2017-10-31 13:58:15

标签: mysql sql join

有两个表T1和T2。它们都有3列,其中2列相同,两个表中的数据相同。让它们成为T1中的ID,C1,C2和T2表中的C1,C2,COM。

事实是T2中存在所有C1数据,但可能错过C2数据。

我需要为每个ID返回一个包含COM的表。

尝试

class UserUpdateView(UpdateView):
    model = get_user_model()
    form_class = forms.UserUpdateForm

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        if self.request.POST:
            context['projectmembership_formset'] = forms.UserProjectMembershipFormSet(
                self.request.POST,
                instance=self.object
            )
        else:
            context['projectmembership_formset'] = forms.UserProjectMembershipFormSet(
                instance=self.object
            )
        return context

    def form_valid(self, form):
        '''Handle saving of the project membership formset
        '''
        context = self.get_context_data()
        project_memberships = context['projectmembership_formset']
        if project_memberships.is_valid():
            self.object = form.save()
            project_memberships.instance = self.object
            project_memberships.save()
            return super().form_valid(form)
        else:
            return self.render_to_response(self.get_context_data(form=form))

但它返回的结果不正确。

1 个答案:

答案 0 :(得分:0)

总结如下:您需要一个且只有一个COM ID(即使它不存在于第二个表中),并且您希望ID按升序排序。

您需要添加连接条件:

SELECT CAST(T1.ID as UNSIGNED) as ID, T2.COM
FROM T1 
LEFT JOIN T2 ON T1.C1 = T2.C1
AND (T1.C2 = T2.C2)  -- The first condition of this row is to handle the null value
OR (T1.C2 NOT IN (SELECT C2 FROM T2) AND T2.C2 = 'NA')
    ORDER BY CAST(T1.ID as UNSIGNED) -- To convert to int and sort ascending

编辑:要对结果进行升序排序,您需要将ID转换为整数,然后对结果进行排序。这是一些documentation

Edit2:这是3和4,这是我认为更好的方法,但我不建议通常这样做