在同一个表

时间:2018-02-26 16:04:06

标签: mysql

我不知道如何用正确的英语提出这个问题。

我有一个查询

select * from user

它返回

id, username, status, owner_id

当我打印

1 - john - 1 - 0
2 - paul - 1 - 0
3 - adam - 1 - 1 (where adam is owned by john)
4 - tony - 1 - 2 (where tony is owned by paul)

我的问题是我要打印所有者名称

我试过

select * from users
foreach($r as $row){
echo $row['id'];
echo $row['username'];
//inside here i did a second select
select username from users where id = $row['owner_id'] 
}

问题是因为数据库非常大,它获得了max_execution时间。

有更好的方法吗?

感谢

2 个答案:

答案 0 :(得分:1)

你可以直接在SQL加入用户两次

  select  a.username, a.status, a.owner_id, b.username
  from user a
  left join user b  on b.id = a.owner_id

答案 1 :(得分:1)

您可以在同一个表上使用LEFT JOIN别名:

select u1.id as u1id, u1.name as u1name, u1.status as u1status,
       u2.id as u2id, u2.name as u2name, u2.status as u2status
from users u1
left join users u2 on u2.id = u1.onwer_id

你会得到:

ud1id = 1, u1name = john, u1status = 1, u2id = NULL, u2name = NULL, u2status = NULL
ud1id = 2, u1name = paul, u1status = 1, u2id = NULL, u2name = NULL, u2status = NULL
ud1id = 3, u1name = adam, u1status = 1, u2id = 1, u2name = john, u2status = 1
...

您还可以获取u1的所有值以及u2的特定字段:

select u1.*, u2.name as owner_name FROM ...