PHP MySQL 合并表问题,读取 fetch

发布于 2024-12-03 21:04:32 字数 385 浏览 0 评论 0原文

我做了一个查询,连接同一个表 - users - 两次, 与加入。

SELECT  * from tbl1 
  JOIN  tbl2 ON tbl2.USER_ID = tbl1.ID 
  JOIN  tbl2 as alias ON tbl1.ID = tbl2.TEACHER_ID 
 WHERE  tbl1.ID = 45

对该表的第一次调用是常规的,第二次我使用 AS 的别名。 当我在 phpMyAdmin 中获得结果时,我看到结果不是被称为别名,而是使用通常的名称,如下所示:

USERNAME => Ted,ID_NUMBER=>33322552,...,USERNAME=>Josh ....

我如何读取该关联数组

I made a query that is joining the same table - users- twice,
with JOINs.

SELECT  * from tbl1 
  JOIN  tbl2 ON tbl2.USER_ID = tbl1.ID 
  JOIN  tbl2 as alias ON tbl1.ID = tbl2.TEACHER_ID 
 WHERE  tbl1.ID = 45

The first call to that table is regular, and the second time I use an alias using AS.
When I get the result in phpMyAdmin, I see the results are not referred to as the alias, but with the usual name, that's like this:

USERNAME => Ted, ID_NUMBER=>33322552, ... ,USERNAME=>Josh ....

How can I read that associative array

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我还不会笑 2024-12-10 21:04:32

在此查询中,您没有使用别名,而是两次引用名为 tbl2 的真实表。这是行不通的。

SELECT * from tbl1 
JOIN tbl2 ON tbl2.USER_ID = tbl1.ID 
JOIN tbl2 as alias ON tbl1.ID = tbl2.TEACHER_ID   
//                              ^^^^ there's no alias here, it's still tbl2 
WHERE tbl1.ID = 45

将其重写为:

SELECT * from tbl1 
JOIN tbl2 AS t2A ON t2A.USER_ID = tbl1.ID 
JOIN tbl2 AS t2B ON tbl1.ID = T2B.TEACHER_ID 
WHERE tbl1.ID = 45

as 关键字是可选的。
这样就不会误解您指的是哪个版本的 tbl2。

两个查询之间的差异

请注意,您还可以将查询 2 重写为:

SELECT * from tbl1 
JOIN tbl2 ON (tbl2.USER_ID = tbl1.ID) OR (tbl2.teacher_ID = tbl1.id)  
WHERE tbl1.ID = 45

在这种情况下,您可以将查询 1 重写为:

SELECT * from tbl1 
JOIN tbl2 ON (tbl2.USER_ID = tbl1.ID) AND (tbl2.teacher_ID = tbl1.id)  
WHERE tbl1.ID = 45

看到区别了吗?

In this query, you are not using an alias, you are refering to a real table called tbl2, twice. This will not work.

SELECT * from tbl1 
JOIN tbl2 ON tbl2.USER_ID = tbl1.ID 
JOIN tbl2 as alias ON tbl1.ID = tbl2.TEACHER_ID   
//                              ^^^^ there's no alias here, it's still tbl2 
WHERE tbl1.ID = 45

Rewrite it to:

SELECT * from tbl1 
JOIN tbl2 AS t2A ON t2A.USER_ID = tbl1.ID 
JOIN tbl2 AS t2B ON tbl1.ID = T2B.TEACHER_ID 
WHERE tbl1.ID = 45

The as keyword is optional.
This way there can be no misunderstanding which version of tbl2 you are refering to.

The difference between the two queries

Note that you can also rewrite query 2 as:

SELECT * from tbl1 
JOIN tbl2 ON (tbl2.USER_ID = tbl1.ID) OR (tbl2.teacher_ID = tbl1.id)  
WHERE tbl1.ID = 45

In that case you would rewrite query 1 as:

SELECT * from tbl1 
JOIN tbl2 ON (tbl2.USER_ID = tbl1.ID) AND (tbl2.teacher_ID = tbl1.id)  
WHERE tbl1.ID = 45

See the difference?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文