简体   繁体   English

从具有2列匹配mysql的3个表中获取结果

[英]Get result from 3 table with 2 column matching mysql

I have 3 tables something like this.. 我有3张桌子,像这样。

Table1.
group_id        admin
................
1         x
2         y
3         z

Table2
group_id        user
....................
1               a
1               b
2               d

Table3
user            status
......................
x               hi
y               hello
z               oh
a               oho
b               sss
d               oops

now you can see that in the above tables we have group id but in the first table i have group admin and second one contains group members.. and following is the result which we want something like this in which both group admin as well as group members we want from a signle group. 现在您可以看到在上面的表中我们具有group id但是在第一个表中我具有组admin,第二个表中包含组成员..以下是我们想要的结果,其中group admingroup members我们想从一个劲儿组。

group_id        user          status
....................................
1               x             hi
1               a             oho
1               b             sss

So,,,Help us to get result something like above.. in mysql 所以,,,,帮助我们得到类似上面的结果..在mysql

If you think of data in terms of data sets... 如果您以数据集的角度来考虑数据...

you have data in tables 1 and 2 that match in columns but you need them together. 您在表1和2中的数据在列中匹配,但是您需要一起使用。 So using a UNION statement you can combine the two tables, alias the result set and join it to your third table to get the desired results. 因此,使用UNION语句可以合并两个表,对结果集进行别名,然后将其连接到第三个表中以获得所需的结果。

This generates a derived table aka inline view (aliased t2) 这将生成派生表,也称为内联视图(别名为t2)

SELECT T2.Group_ID, T2.user, T3.Status
FROM (SELECT group_ID, Admin as user 
      FROM table1
      UNION ALL
      SELECT group_ID, user 
      FROM table2
     ) t2
INNER JOIN table3 t3
 on t3.group_Id = T2.GroupID

Try this? 尝试这个?

SELECT table1.group_id, table3.user, table3.status 
FROM Table1, table2
    LEFT JOIN table3 ON (table1.admin = table3.user OR table2.user = table3.user)
WHERE table1.group_id = table2.group_id AND table1.group_id = 1
GROUP BY table3.user

I am assuming every group has an admin and every user has an entry in table 3. 我假设每个组都有一个管理员,每个用户都有一个表3中的条目。

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

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