如何为预期的给定结果构建查询

时间:2016-03-12 20:01:42

标签: mysql sql select

我有三张桌子,

Fiddle Demo

问题是,它为所有其他行提供了另一个没有可用记录的null

如果可以合并数据,

id  qtype cyu
1   1     simple
2   2     op

2 个答案:

答案 0 :(得分:1)

您可以使用coalesce获取非空列值:

class TrafficForm(ModelForm):
    class Meta:
        model = Traffic
        fields = ['sessions', 'new_users', 'reminder', 'campaigns', 'new_sales', 'sales_renewals']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['sessions'].widget.attrs.update({
            'placeholder': 'Sessions',
            ...
        })

        for field in iter(self.fields):
            self.fields[field].widget.attrs.update({
                'class': 'form-control placeholder-no-fix'
            })


def traffic_create(request, template_name='traffic_form.html'):
    form = TrafficForm(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect('traffic_list')
    return render(request, template_name, {'form': form})


def traffic_list(request, template_name='traffic_list.html'):
    traffic = Traffic.objects.all()
    data = {}
    data['object_list'] = traffic
    return render(request, template_name, data)


def traffic_update(request, pk, template_name='traffic_form.html'):
    traffic = get_object_or_404(Traffic, pk=pk)
    form = TrafficForm(request.POST or None, instance=traffic)
    if form.is_valid():
        form.save()
        return redirect('traffic_list')
    return render(request, template_name, {'form': form})


def traffic_delete(request, pk, template_name='traffic_confirm_delete.html'):
    traffic = get_object_or_404(Traffic, pk=pk)
    if request.method == 'POST':
        traffic.delete()
        return redirect('traffic_list')
    return render(request, template_name, {'object': traffic})

<强> SQLFiddle

答案 1 :(得分:1)

使用COALESCE返回第一个非NULL值:

coalesce( qs.cyu, qo.cyu )

请参阅fiddle