gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:29:01 25 4
gpt4 key购买 nike

我有下面提到的两个表。

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 |

最佳答案

试试这段代码。

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<> fiddle here

关于mysql - 如何在mysql中连接基于两列的表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51532977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com