MySQL内部连接2表和计数表2来自表1中的ID

时间:2017-03-08 19:46:45

标签: mysql sql inner-join

我有两张桌子,想加入他们两个。然后我想从表B得到计数总结果,如果表A中的一个或多个数据在表B上具有相同的ID。这是示例。

enter image description here

enter image description here

enter image description here

我已经尝试过这样,但它只给我两个结果,而不是我想要的结果:

class RegistrarUsuario(FormView):
form_class    = UserForm
template_name =  'home/registrar.html'
success_url   = '/registrar'

def form_valid(self,form):
    user = form.save()
    email = form.cleaned_data['email']
    direccion      = form.cleaned_data['direccion']
    nombre_negocio = form.cleaned_data['negocio']
    category       = form.cleaned_data['categoria']
    encargado      = form.cleaned_data['encargado']
    telefono       = form.cleaned_data['telefono']
    imagen         = form.cleaned_data['imagen']
    lat            = form.cleaned_data['lat']
    lng            = form.cleaned_data['lng']
    user_profile = Perfil(user=user,nombre_negocio=nombre_negocio,encargado=encargado,imagen=imagen,direccion=direccion,telefono=telefono,email=email,category=category,lat=lat,lng=lng)

    user.save()
    user_profile.save()

    return super(RegistrarUsuario, self).form_valid(form) 

2 个答案:

答案 0 :(得分:1)

你应该使用左连接和案例

  SELECT 
  table_a.id_tblA,
  table_a.Name,
  sum(case when table_b.id_tblB is null then 0 else 1 end) total
  FROM  table_a
  left  join table_b on table_b.id_tblA = table_a.id_tblA
  group by table_a.id_tblA, table_a.Name

答案 1 :(得分:1)

试试这个

SELECT
    table_a.id_tblA, table_a.tblA_name, 
    (SELECT count(*) FROM table_b WHERE table_b.id_tblA = table_a.id_tblA)
FROM
    table_a;