在 php 和 MySQL 中匹配并返回行
我很想得到一些帮助。我正在使用 php 和 MySQL 来构建一个网站。我目前有 3 个表,我将在示例中包含更少的表。基本上我有一个用户表、一个组表和一个组链接表。我拥有的是用户表中的 uid。
我应该如何在 php 中处理它,这样我就可以,比方说:将 users-uid 与 grouplink-uid 匹配,获取与之匹配的 grouplink-gid,将 grouplink-gid 与 groups-gid 匹配并返回 groups-grpname ?并进行 while 循环,以便显示与用户关联的所有组名称。
预先感谢那些愿意伸出援助之手的人。
用户
-------
| uid |
-------
| 1 |
-------
组
---------------
| gid |grpname|
---------------
| 1 | grp1 |
---------------
| 2 | grp2 |
---------------
grouplink
-------------------
| glid| uid | gid |
-------------------
| 1 | 1 | 1 |
-------------------
| 2 | 1 | 2 |
-------------------
uid 是用户中的 uid 的 fk,而 gid 是组中的 gid 的 fk
I would love to get some help with this. I'm using php and MySQL to build a website. I currently have 3 tables, I'll include less in the examples. Basically I have a users table, a groups table and a grouplink table. What I have is the uid from the users table.
How should I go about it in php so I could, let's say: match users-uid to grouplink-uid, get the grouplink-gid it matches with, match grouplink-gid to groups-gid and return groups-grpname? And goes on a while loop so all group names the user is associated with are displayed.
Thanks in advance to those who will be willing to extend a hand.
users
-------
| uid |
-------
| 1 |
-------
groups
---------------
| gid |grpname|
---------------
| 1 | grp1 |
---------------
| 2 | grp2 |
---------------
grouplink
-------------------
| glid| uid | gid |
-------------------
| 1 | 1 | 1 |
-------------------
| 2 | 1 | 2 |
-------------------
uid is fk to uid in users while gid is fk to gid in groups
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这只是一个简单的 2 路联接查询:
联接查询结果的实际检索与单个表查询没有什么不同 - 您只是需要处理更多字段。
That's just a simple 2-way join query:
the actual retrieval of a joined query result is no different than a single table query - you've just got more fields to deal with.
将为您提供所需内容的 SQL 查询如下所示(假设 grouplink 表中没有空值):
The SQL query that will get you what you're looking for goes something like this (assuming no null values in the grouplink table):
这是一种方法:
Here is one way:
当用户 ID 位于变量
$iUserId
中时,您可以查询以下 sql 字符串:现在与用户关联的所有组都在数组
$aGroups
中。When the user-id is in the variable
$iUserId
you could query following sql string:Now all groups associated with the user are in the array
$aGroups
.