Sql recursion without recursion

前端 未结 6 1364
故里飘歌
故里飘歌 2020-12-16 23:18

I have four tables

create table entities{
integer id;
string name;
}

create table users{
integer id;//fk to entities
string email;
}

create table groups{
i         


        
6条回答
  •  囚心锁ツ
    2020-12-16 23:38

    Can you clarify the difference between an entity and a user? Otherwise, your tables look OK. You are making an assumption that there is a many-to-many relationship between groups and entities.

    In any case, with standard SQL use this query:

    SELECT name, group_id
    FROM entities JOIN group_members ON entities.id = group_members.entity_id;
    

    This will give you a list of names and group_ids, one pair per line. If an entity is a member of multiple groups, the entity will be listed several times.

    If you're wondering why there's no JOIN to the groups table, it's because there's no data from the groups table that isn't already in the group_members table. If you included, say, a group name in the groups table, and you wanted that group name to be shown, then you'd have to join with groups, too.

    Some SQL variants have commands related to reporting. They would allow you to list multiple groups on the same line as a single entity. But it's not standard and wouldn't work across all platforms.

提交回复
热议问题