简体   繁体   English

SQL n:m关系

[英]SQL n:m relation

I have the following tables (unrelated columns left out): 我有下表(省略了不相关的列):

studios:
id | user_id
 1 |       1
 2 |       1

equipment:
id
 1
 2

studio_equipment:
id | studio_id | equipment_id
 1 |         1 |            1
 2 |         1 |            1

I have "studios" and "equipment". 我有“工作室”和“设备”。 A studio belongs to a user. 工作室属于用户。 Equipment can be assigned to studios (studio_equipment table). 可以将设备分配给工作室(studio_equipment表)。 An equipment can be assigned multiple times to a studio but there can also be studios that have no equipment yet. 可以将设备多次分配给工作室,但也可以有尚无设备的工作室。

I want to retrieve all studios for a certain user together with all the possible equipment that could be assigned to these studios. 我想检索某个用户的所有工作室以及可以分配给这些工作室的所有可能的设备。 If an equipment has already been assigned to a studio, then show this aswell. 如果已经将设备分配给工作室,则也要显示此设备。

For the example above that would mean the following (for user_id 1): 对于上面的示例,这意味着以下内容(对于user_id 1):

desired results:
studio.id | equipment.id | studio_equipment.id
        1 |            1 |                   1
        1 |            1 |                   2
        1 |            2 |                null
        2 |            1 |                null
        2 |            2 |                null

This is my SQL statement thus far: 到目前为止,这是我的SQL语句:

SELECT `s`.*, `e`.*, `se`.*
FROM (`studios` AS s)
LEFT JOIN `studio_equipment` AS se ON `s`.`id`=`se`.`studio_id`
LEFT OUTER JOIN `equipment` AS e ON `se`.`equipment_id`=`e`.`id`
WHERE `s`.`user_id` =  '1'

But this does not retrieve all the data i want. 但这不会检索我想要的所有数据。 For Example studio 2 is retrieved but not paired with all the possible equipment. 例如,示例工作室2被检索但未与所有可能的设备配对。

Thanks in advance for your help! 在此先感谢您的帮助!

SELECT 
    s.id  AS studio_id, 
    e.id  AS equipment_id, 
    se.id AS studio_equipment_id
FROM 
     studios AS s
  CROSS JOIN 
     equipment AS e
  LEFT JOIN 
     studio_equipment AS se 
       ON  se.studio_id = s.id
       AND se.equipment_id = e.id ;

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

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