假设我有一个名为users
的表,其中包含以下列:user_id
,user_name
,user_created_by
。
+------------------+----------------------+-------------------+
| user_id + user_name + user_created_by +
+------------------+----------------------+-------------------+
| 1 | John | 1 |
| 2 | Ann | 1 |
| 3 | Paul | 2 |
| 4 | King | 2 |
| 5 | Dirk | 3 |
+------------------+----------------------+-------------------+
user_created_by
的值是创建该记录的user_id
。现在,我想进行一个查询,结果是在一个特定的行上添加了列,我们假设user_created_by_name
是user_name
中user_id
的{{1}}。假设我们要获取“ Paul” 的记录以及创建者(名称)(临时新列)。为了便于理解,这是我的预期结果:
user_created_by
这是我使用codeigniter的查询:
+----------+--------------+-------------------+------------------------+
| user_id | user_name | user_created_by | user_created_by_name |
+----------+--------------+-------------------+------------------------+
| 3 | Paul | 2 | Ann |
+----------+--------------+-------------------+------------------------+
但是我的结果是:
$query=$this->db->query("SELECT *,
(SELECT user_name FROM users WHERE user_id = user_created_by)
AS "user_created_by_name" FROM users WHERE user_id=3);
答案 0 :(得分:1)
使用自我加入
select u1.user_id, u1.name as user_name,
u2.user_created_by
,u2.user_name as createdby from users u1
join users u2 on u1.user_id=u2.user_created_by
where u1.user_id=3
答案 1 :(得分:1)
这将起作用:
SELECT a.user_id as User_id,
a.user_name as Name,
b.user_id as Created_by_user_id,
b.user_name as Created_by_name
FROM users AS a
INNER JOIN users AS b
ON a.user_id = b.user_created_by
WHERE a.user_id = 3
它称为自联接,在合并同一张表的两条记录时使用。
答案 2 :(得分:1)
您可以使用JOIN解决此问题。
$sql = "SELECT users.user_id, users.user_name, user_created_by_name.user_name,
FROM users JOIN users AS user_created_by_name ON users.user_id = user_created_by_name.user_id WHERE users.user_id = 3";
$query=$this->db->query($sql);
如果您有不是由其他用户创建的用户,请改用LEFT JOIN:
$sql = "SELECT users.user_id, users.user_name, user_created_by_name.user_name,
FROM users LEFT JOIN users AS user_created_by_name ON users.user_id = users.user_id WHERE user_created_by_name.user_id = 3";
$query=$this->db->query($sql);
答案 3 :(得分:1)
您应该使用自我连接(两次连接同一张表),使用别名将表作为不同的数据集
SELECT a.user_id, a.user_name, a.user_created_by, b.user_name as user_created_by_name
from users a
inner join user b on a.user_created_by = b.user_id
where a.user_id = 3