同时选择两个表

时间:2019-10-30 15:07:19

标签: sql database postgresql

我有 users user_groups 表,如下所示:

用户

id - PK
name
timestamp

user_groups

user_1 - Foreign key to users id
user_2 - Foreign key to users id
user_3 - Foreign key to users id
type

我有一个ID为1的用户。我想选择该用户加入的所有组,组成员的名字和用户组的类型。我可以只执行一个查询吗?实现这一目标的最佳方法是什么?

样本数据

用户

id - 1
name - Jeff

id - 2
name - Mehmet

id - 3
name - Walter

用户组

user_1 - 1
user_2 - 2
user_3 - null
type - 1

user_1 - 1
user_2 - 2
user_3 - 3
type - 1

user_1 - 1
user_2 - 3
user_3 - null
type - 2

输出应如何:

[{
type: 1,
name: ["Jeff", "Mehmet"]
},

{
type: 1,
name: ["Jeff","Mehmet","Walter"]
},

{
type: 2,
name: ["Jeff", "Mehmet"]
}]

1 个答案:

答案 0 :(得分:1)

您需要多个联接和某些数组功能:

ERROR: Command errored out with exit status 1:
command: 'C:\Users\yeetgod\AppData\Local\Programs\Python\Python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\yeetgod\\AppData\\Local\\Temp\\pip-install-aims1y79\\pocketsphinx\\setup.py'"'"'; __file__='"'"'C:\\Users\\yeetgod\\AppData\\Local\\Temp\\pip-install-aims1y79\\pocketsphinx\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\yeetgod\AppData\Local\Temp\pip-record-fcvz7sp8\install-record.txt' --single-version-externally-managed --compile
         cwd: C:\Users\yeetgod\AppData\Local\Temp\pip-install-aims1y79\pocketsphinx\
    Complete output (6 lines):
    running install
    running build_ext
    building 'sphinxbase._sphinxbase' extension
    swigging deps/sphinxbase/swig/sphinxbase.i to deps/sphinxbase/swig/sphinxbase_wrap.c
    swig.exe -python -modern -threads -Ideps/sphinxbase/include -Ideps/sphinxbase/include/sphinxbase -Ideps/sphinxbase/include/win32 -Ideps/sphinxbase/swig -outdir sphinxbase -o deps/sphinxbase/swig/sphinxbase_wrap.c deps/sphinxbase/swig/sphinxbase.i
    error: command 'swig.exe' failed: No such file or directory
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'C:\Users\yeetgod\AppData\Local\Programs\Python\Python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\yeetgod\\AppData\\Local\\Temp\\pip-install-aims1y79\\pocketsphinx\\setup.py'"'"'; __file__='"'"'C:\\Users\\yeetgod\\AppData\\Local\\Temp\\pip-install-aims1y79\\pocketsphinx\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\yeetgod\AppData\Local\Temp\pip-record-fcvz7sp8\install-record.txt' --single-version-externally-managed --compile Check the logs for full command output.