我这里有3张桌子,即:
person (
id int PRIMARY KEY
,fullname text)
phonenumber (
id int PRIMARY KEY
,personid int REFERENCES person(id)
,phonetypeid REFERENCES phonetype(id)
,number text)
phonetype (
id int PRIMARY KEY
,phonetype text) -- phonetype 'Home', 'Cell', 'Fax', 'Main' etc.
每个都可以在表person
中存储多个号码,并且在phonenumber
表中具有不同的电话类型phonetype
:
| fullname | number | phonetype |
| Erwin Macale | (671)632-3909 | Home |
| Erwin Macale | (671)632-3909 | Cell |
| Erwin Macale | (671)632-3909 | Main |
我只想显示具有以下条件的每个人的电话号码:
- 如果他有一个“家庭”电话类型号码,则只显示家庭类型删除他所有其他电话类型号码。
- 如果他没有“家庭”号码,则只显示他的“手机”号码,然后删除他所有的其他(“传真”、“主要”等)号码。
- 一个人可以没有电话号码。
我创建了一个临时表,其中包含fullname, number, phonetype
命名testable
然后从这里我分隔所有电话类型号码,例如:
CREATE TEMP TABLE home AS SELECT * FROM testable WHERE phonetype ILIKE 'home';
CREATE TEMP TABLE cell AS SELECT * FROM testable WHERE phonetype ilike 'cell';
CREATE TEMP TABLE main AS SELECT * FROM testable WHERE phonetype ilike 'main';
CREATE TEMP TABLE fax AS SELECT * FROM testable WHERE phonetype ilike 'fax';
CREATE TEMP TABLE work AS SELECT * FROM testable WHERE phonetype ilike 'work';
CREATE TEMP TABLE neighbor AS SELECT * FROM testable WHERE phonetype ilike 'neighbor';
CREATE TEMP TABLE other AS SELECT * FROM testable WHERE phonetype ilike 'other';
CREATE TEMP TABLE unknown AS SELECT * FROM testable WHERE phonetype ilike 'unknown';
然后创建另一组我认为满足上述条件的临时表:
CREATE TEMP TABLE all_cell AS SELECT * FROM cell EXCEPT SELECT * FROM home;
CREATE TEMP TABLE all_main AS (SELECT * FROM main) EXCEPT (SELECT * FROM home UNION SELECT * FROM cell);
CREATE TEMP TABLE all_fax AS (SELECT * FROM fax) EXCEPT (SELECT * FROM home UNION SELECT * FROM cell UNION SELECT * FROM main);
CREATE TEMP TABLE all_work AS (SELECT * FROM work) EXCEPT (SELECT * FROM home UNION SELECT * FROM cell UNION SELECT * FROM main UNION SELECT * FROM fax);
CREATE TEMP TABLE all_neighbor AS (SELECT * FROM neighbor) EXCEPT (SELECT * FROM home UNION SELECT * FROM cell UNION SELECT * FROM main UNION SELECT * FROM fax UNION SELECT * FROM work);
CREATE TEMP TABLE all_other AS (SELECT * FROM other) EXCEPT (SELECT * FROM home UNION SELECT * FROM cell UNION SELECT * FROM main UNION SELECT * FROM fax UNION SELECT * FROM work UNION SELECT * FROM neighbor);
CREATE TEMP TABLE all_unknown AS (SELECT * FROM unknown) EXCEPT (SELECT * FROM home UNION SELECT * FROM cell UNION SELECT * FROM main UNION SELECT * FROM fax UNION SELECT * FROM work UNION SELECT * FROM neighbor UNION SELECT * FROM other);
最后选择最后一组临时表的所有并集:
SELECT fullname, number, phonetype FROM (
SELECT * FROM home
UNION
SELECT * FROM all_cell
UNION
SELECT * FROM all_main
UNION
SELECT * FROM all_fax
UNION
SELECT * FROM all_work
UNION
SELECT * FROM all_neighbor
UNION
SELECT * FROM all_other
UNION
SELECT * FROM all_unknown
) AS t1
ORDER BY t1.fullname, t1.phonetype;
满足我的条件的步骤是否正确?我仍然从一个人那里得到不同的电话类型值。