我有两个表,如下所述。
user table
id | username | password | status |
1 | Prajna | ***** | active |
2 | Akshata | ***** | active |
3 | Sanjana | ***** | inactive |
test table
id | project_name | created_by (user id) | edited_by (user id) |
1 | Test | 1 | 2 |
2 | Trial | 1 | 1 |
3 | Pro1 | 2 | 2 |
我正在尝试以下查询。
select project_name, user.username from test join user on user.id=test.created_by where user.status='active';
我想要下面的结果
我要检索以下结果 我该如何找回?
project_name | username(created by) | username (edited by) |
Test | Prajna | Akshata |
Trial | Prajna | Prajna |
Pro1 | Akshata | Akshata |
答案 0 :(得分:3)
尝试此代码。
create table `user` ( `id` int, `username` varchar(20), `password` varchar(20), `status` varchar(20) )
insert into `user` (`id`,`username`,`password`,`status`) values (1, 'Prajna', '*****', 'active'), (2, 'Akshata', '*****', 'active'), (3, 'Sanjana', '*****', 'inactive')
create table `test` ( `id` int, `project_name` varchar(20), `created_by` int, `edited_by` int )
insert into `test` (`id`,`project_name`,`created_by`,`edited_by`) values (1, 'Test', 1, 2), (2, 'Trial', 1, 1), (3, 'Pro1', 2, 2)
SELECT `t`.`project_name`, `ua`.`username` as 'username (created by)' , `ub`.`username` as 'username (edited by)' FROM `test` `t` JOIN `user` `ua` ON `t`.`created_by` = `ua`.`id` JOIN `user` `ub` ON `t`.`edited_by` = `ub`.`id` WHERE `ua`.`status` = 'active' AND `ub`.`status` = 'active' order by `t`.`id`
project_name | username (created by) | username (edited by) :----------- | :-------------------- | :------------------- Test | Prajna | Akshata Trial | Prajna | Prajna Pro1 | Akshata | Akshata
db <>提琴here
答案 1 :(得分:0)
SELECT
test.project_name, user.username
FROM test
INNER JOIN user
ON user.id = test.created_by
WHERE user.status='active';
PS:您在这里遇到错误user.id = test = created_by
答案 2 :(得分:0)
您需要sub-query
并使用join
在这两个子查询之间联接
select project_name,created_by,edited_by from
(
select u.id,project_name, u.username as created_by from user u left join test t1 on
u.id= t1.created_by
where user.status='active'
) Table1
inner join
(
select u.id,project_name, u.username as edited_by from user u left join test t2 on
u.id= t2.created_by
where user.status='active'
) table2 on Table1.project_name=table2.project_name