我有一个SQLite表,用于存储有关公司/分支机构的信息,结构如下:
id | id_branch | username | position |
-------+-------------+------------+----------
1 | 111 | ana | manager
2 | 222 | steph | officer
3 | 111 | carl | officer
4 | 111 | alex | officer
给出用户名,我需要根据以下规则检索ID:
如何在SQL中执行此条件选择语句?
答案 0 :(得分:1)
将其作为union all
查询是很诱人的。但是,您可以通过简单的自连接检测这些条件:
select t.*
from t cross join
t tu
where tu.username = ? and
( (tu.position = 'manager' and t.branch_id = tu.branch_id) or
(tu.position = 'officer' and t.id = tu.id)
);
答案 1 :(得分:1)
您可以在某些情况下尝试使用自联接。
模式(SQLite v3.18)
CREATE TABLE T (
id int,
id_branch int,
username varchar(50),
position varchar(50)
);
insert into T values (1,111,'ana' ,'manager');
insert into T values (2,222,'steph' ,'officer');
insert into T values (3,111,'carl' ,'officer');
insert into T values (4,111,'alex' ,'officer');
查询#1
SELECT t2.*
FROM T t1
INNER JOIN T t2 On
t1.id_branch = t2.id_branch and t1.position = 'manager'
or
t1.id = t2.id and t1.position = 'officer'
where t1.username = 'ana';
| id | id_branch | username | position |
| --- | --------- | -------- | -------- |
| 1 | 111 | ana | manager |
| 3 | 111 | carl | officer |
| 4 | 111 | alex | officer |