简体   繁体   English

MySQL,SQL,PHP,我可以从两个表中获取数据,再将第三个表中的数据

[英]MySQL, SQL, PHP can I bring data from two tables joined by a third

I've got an issue I have 3 tables: 我有一个问题,我有3张桌子:

1 table named "members" (it has the members data, ID, Username, Password)
2 table named "schools" (it has list of schools ID, School_Name, School_Number)
3 table named "members_schools" (Here I two columns: User_ID, School_ID)

so I'm in a middle of a mess, I need to realize a sorting or grouping system for example: School Of St.Peter, Number 8, has an ID 1 in "schools" table 所以我陷入混乱,我需要实现一个排序或分组系统,例如:St.Peter School,8号,“ schools”表中的ID为1

users have the right to choose ,from a list, this school and then I made a query to save their choice in "members_schools" something like: 用户有权从列表中选择这所学校,然后我查询将其选择保存在“ members_schools”中,例如:

User_ID  ::  Scool_ID
4        ::   1

This should bring back that: the user with ID:4 is attending the school with ID:1 which is here "School Of St.Peter" 这应该带回来:ID:4的用户正在ID:1的学校上学,这里是“ St.Peter学校”

now I tried to LEFT JOIN the tables among each others, but so far no luck!! 现在我试图让其他人彼此之间保持联系,但是到目前为止还没有运气! I'm confused how to realize this thing, retrieving the data from the three tables and show them on a page in this order. 我很困惑如何实现这件事,从三个表中检索数据并按此顺序在页面上显示它们。

School               ::     No. Attenders
School Of St.Peter   ::     "NUMBER OF MEMBERS WHO HAVE APPLIED FOR THIS SCHOOL"

Thank you guys. 感谢大伙们。

SELECT schools.School_name AS `School`, COUNT(0) AS `Nr. Attenders`
FROM schools INNER JOIN members_schools ON schools.id = members_schools.School_ID
GROUP BY schools.School_name

Would give you the nr of members per school The members table is not relevant for the number of attenders. 将为您提供每所学校的会员人数。会员表与参加人数无关。

You don't need to use three tables until details of all users is required. 在不需要所有用户的详细信息之前,您不需要使用三个表。 To get a count we need to use only schools and member_schools table. 为了获得计数,我们只需要使用schoolsmember_schools表。

Use LEFT JOIN and then count the user_id in result 使用LEFT JOIN ,然后计算结果中的user_id

SELECT schools.School_Name AS School, IFNULL(COUNT(member_schools.User_ID),0) AS Number_of_Attenders
FROM schools LEFT JOIN member_schools
ON schools.ID = member_schools.School_ID
GROUP BY schools.School_name

Sample Output 样本输出

School               ::     Number_of_Attenders
School Of St.Peter   ::     4

To show username of all members, use GROUP_CONCAT 要显示所有成员的用户名,请使用GROUP_CONCAT

SELECT schools.School_Name AS School, GROUP_CONCAT(members.Username) AS Attenders
FROM schools LEFT JOIN member_schools
ON schools.ID = member_schools.School_ID
INNER JOIN members
ON member_schools.User_ID = members.ID
GROUP BY schools.School_name

Sample Output 样本输出

School               ::     Attenders
School Of St.Peter   ::     Isaac, Kevin, Rockse, Aish

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

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