我想根据 MySQL 上的左表创建右表。
SELECT A.id AS id, B.name AS name, A.name as loca FROM tst A, tst B WHERE A.id = B.loca;
但是,这无法选择位置字段不在 id 字段中的行。要选择不需要替换位置名称的行,我该怎么做?我需要你的提示。
谢谢你的指导。
答案1
select
l1.id,
coalesce(l2.name, l1.loca) as loca
from
loca l1 left outer join
loca l2
on (l1.loca = l2.id);
|----+----------|
| id | loca |
|----+----------|
| 1 | ROOM1 |
| 2 | desk 1 |
| 3 | desk 1 |
| 4 | ROOM2 |
| 5 | desk 2 |
| 6 | case |
| 7 | drawer 1 |
| 8 | ROOM3 |
|----+----------|
鉴于此表定义:
create temp table loca (
id text,
name text,
loca text
);
insert into loca values
(1, 'desk 1', 'ROOM1'),
(2, 'drawer 1', '1'),
(3, 'drawer 2', '1'),
(4, 'desk 2', 'ROOM2'),
(5, 'case', '4'),
(6, 'redpen', '5'),
(7, 'blkpen', '2'),
(8, 'printer', 'ROOM3');