如何在mysql中实现基于两列的表连接?

vulvrdjw  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(282)

我有下面提到的两张table。

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              |
qnakjoqk

qnakjoqk1#

你需要 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

q3qa4bjr

q3qa4bjr2#

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\u by。

ou6hu8tu

ou6hu8tu3#

试试这个代码。

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<>在这里摆弄

相关问题