MySQL join tables where table name is a field of another table

前端 未结 3 1259
太阳男子
太阳男子 2021-01-12 08:30

I have 5 tables. One primary and 4 additional (they have different columns).

  1. objects
  2. obj_mobiles
  3. obj_tablets
  4. obj_computers
3条回答
  •  情话喂你
    2021-01-12 08:59

    If objects is a parent table it means that objects.ID is a unique object. Right? All other items (mobiles, tablets, computers) are child ones for object and mobile and tablet cannot have the same ID. If so, it is enough to use this simple query -

    SELECT * FROM objects o
      LEFT JOIN obj_mobiles m
        ON o.id = m.ID
      LEFT JOIN obj_tablets t
        ON o.id = t.ID
      LEFT JOIN obj_computers c
        ON o.id = c.ID
    

    Add WHERE clause to filter types, e.g.: WHERE o.type = 'mobile'.

提交回复
热议问题