数据库查询复杂的select语句

时间:2011-08-01 10:22:21

标签: mysql sql

我的桌子有id名称和经理ID

id  name  manager_id
1  myName  4
2  alex    3
3  brain   2
4  someone 1

现在我必须编写显示结果的查询

myname someone
alex brain
brain alex
someone myname

表示我们必须根据Id

显示name和mnager Name

3 个答案:

答案 0 :(得分:5)

加入表格:

SELECT t1.name, t2.name FROM my_table AS t1 
    LEFT JOIN my_table AS t2 ON( t1.manager_id = t2.id )

答案 1 :(得分:4)

这会让你回归吗?

SELECT
  t1.name AS Name,
  t2.name AS manager
FROM tab t1
  JOIN tab t2 ON(t1.manager_id = t2.id)

答案 2 :(得分:2)

SELECT
  employee.name,
  manager.name
FROM
  tablename employee
INNER JOIN
  tablename manager
ON
  employee.manager_id = manager.id

tablename替换为实际的表名。