比较select 上同table (mysql)
Comparative select on the same table (mysql)
我真的是 mysql 的新手,我正在尝试做一个简单的 select,但我无法弄清楚。
这就是我所拥有的:
I got this in a Table named Control:
| CODE | OFFICE |
| 1 | usa |
| 2 | usa |
| 3 | usa |
| 4 | usa |
| 5 | usa |
| 1 | china |
| 3 | china |
| 4 | china |
And I need get this:
| CODE | OFFICE |
| 2 | usa |
| 5 | usa |
然后,SELECT code,office WHERE codes are still not registered with office = china.
我必须进行自连接或类似的操作或使用 GROUP BY 语句吗?
我被困在这里...我真的很感激任何帮助。
我猜这是可行的
create table Test(id integer, code integer, office varchar(100));
insert into Test(id, code, office) values(1, 1, "usa"),(2, 2, "usa"),(3, 3, "usa"),(4, 4, "usa"),(5, 5, "usa"),(6, 1, "china"),(7, 3, "china"),(8, 4, "china");
select * from Test;
Select * from Test where code NOT IN (select code from Test where office = "china");
您已经使用了子查询。
您可以在 Code
上执行 "Self-Left-Join",并仅考虑右侧未找到匹配项的那些行,即 ,右侧值 IS NULL
SELECT
tleft.*
FROM Control AS tleft
LEFT JOIN Control AS tright
ON tright.Code = tleft.Code AND
tright.Office = 'china'
WHERE tleft.Office = 'usa' AND
tright.Code IS NULL -- this filters no matching code found in china
我真的是 mysql 的新手,我正在尝试做一个简单的 select,但我无法弄清楚。
这就是我所拥有的:
I got this in a Table named Control:
| CODE | OFFICE |
| 1 | usa |
| 2 | usa |
| 3 | usa |
| 4 | usa |
| 5 | usa |
| 1 | china |
| 3 | china |
| 4 | china |
And I need get this:
| CODE | OFFICE |
| 2 | usa |
| 5 | usa |
然后,SELECT code,office WHERE codes are still not registered with office = china.
我必须进行自连接或类似的操作或使用 GROUP BY 语句吗? 我被困在这里...我真的很感激任何帮助。
我猜这是可行的
create table Test(id integer, code integer, office varchar(100));
insert into Test(id, code, office) values(1, 1, "usa"),(2, 2, "usa"),(3, 3, "usa"),(4, 4, "usa"),(5, 5, "usa"),(6, 1, "china"),(7, 3, "china"),(8, 4, "china");
select * from Test;
Select * from Test where code NOT IN (select code from Test where office = "china");
您已经使用了子查询。
您可以在 Code
上执行 "Self-Left-Join",并仅考虑右侧未找到匹配项的那些行,即 ,右侧值 IS NULL
SELECT
tleft.*
FROM Control AS tleft
LEFT JOIN Control AS tright
ON tright.Code = tleft.Code AND
tright.Office = 'china'
WHERE tleft.Office = 'usa' AND
tright.Code IS NULL -- this filters no matching code found in china