[英]Issue Building PHP / MySQL Join Query
I am having some issues trying to construct this JOIN query. 我在尝试构造此JOIN查询时遇到一些问题。 Any help is greatly appreciated!
任何帮助是极大的赞赏! Thanks!
谢谢!
I have 3 tables here. 我这里有3张桌子。 Table A houses our "users."
表A容纳了我们的“用户”。 They are identified by the id number.
它们由ID号标识。 Table C houses locations identified by an id number.
表C包含由ID号标识的位置。 Table B contains the connection between Table A and Table C. uid is the id of the user and lid is the id of the location.
表B包含表A和表C之间的连接。uid是用户的ID,而lid是位置的ID。 The user might be associated with multiple locations.
该用户可能与多个位置相关联。
I need to build a query that will take the id of the user, find all of the locations that user's id is associated with and return them. 我需要构建一个查询,该查询将获取用户的ID,查找与该用户ID相关联的所有位置,然后将其返回。
Table A 表A
| id | name |
-----------------------------
| 0 | steven |
-----------------------------
| 1 | etc |
-----------------------------
Table B 表B
| id | uid | lid |
-------------------------------------------
| 0 | 0 | 1 |
-------------------------------------------
| 1 | 1 | 1 |
-------------------------------------------
Table C 表C
| id | location_name |
----------------------------------
| 0 | santa monica |
----------------------------------
| 1 | hamptons |
----------------------------------
You can Try like below 您可以尝试如下
SELECT
A.id as user_id,
A.name as user_name,
C.location_name as location
FROM
TableA A
JOIN
TableB B ON A.id = B.uid
JOIN
TableC C ON B.lid = C.id
WHERE
A.id = 0;
SELECT u.id, u.name, l.id, l.location_name
FROM users u
JOIN connection c
ON c.uid = u.id
JOIN locations l
ON c.lid = l.id
WHERE u.id=?
GROUP BY l.id;
select A.name, C.location_name from B inner join A on B.uid=A.id inner join C on B.lid= C.id where A.id='".$id."' ;
$ id是您输入的用户名
I would say you remove that table B and have only table A and table C. 我会说您删除该表B,而只有表A和表C。
Table A 表A
| id | name |
-----------------------------
| 0 | steven |
-----------------------------
| 1 | etc |
-----------------------------
Table C 表C
| id | location_name | uid |
-------------------------------------------
| 0 | santa monica | 0 |
-------------------------------------------
| 1 | hamptons | 1 |
-------------------------------------------
The table C which I have proposed has a foreign key which references table A's id
我建议的表C具有引用表A的
id
的外键
Now you can have a query like, 现在,您可以进行如下查询:
select * from tableA A
inner join
tableB B on
A.id = B.uid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.