SQL需要帮助的初学者就是问题所在。对于我在postgresql上测试的任何数据库,可以是SQL stmt。 我有2个SQL表的以下问题:
表编号1
.....................
|Boy Name| Girl Name |
|--------------------|
|Michael | Anne |
|Michael | Misty |
|Michael | Simone |
|Michael | Diane |
|Michael | Ariel |
|Jack | Misty |
|Jack | Simone |
|Jack | Anne |
|Sam | Simone |
|Sam | Misty |
|Sam | Anne |
|Sam | Mini |
|Sam | Valery |
----------------------
表编号2
..................................
|Boy Name | Anne | Misty | Simone|
|--------------------------------|
|Michael | yes | no | no |
|Jack | yes | yes | yes |
|Sam | no | no | yes |
..................................
(IDK就像一个问题:一个女孩喜欢特定的男孩。可以是,不,或没有。)
期望的结果
查询返回2列的表: - 男孩通过2号桌从女孩身上获得的每一个“不”的行。
.....................
|Boy Name| Girl Name |
|--------------------|
|Michael | Misty |
|Michael | Simone |
|Sam | Misty |
|Sam | Anne |
----------------------
您可以将结果视为一个新行a,其中包含男孩名称的列,另一个名称为女孩的名称,表格编号为2中为“否”。
答案 0 :(得分:1)
首先,我建议使用不同的表格设计:
CREATE TABLE person
(
id INT PRIMARY KEY,
person_name VARCHAR(200),
sex CHAR(1)
);
-- possible record: 1, 'John', 'M'; 2, 'Mary', 'F';
CREATE TABLE person_symphaty
(
person_id INT, -- FK to person table
symphaty_person_id INT -- FK to person table
);
-- you will store here if the person likes another one. 1 point here is that you can store that person doesn't like somebody, then you need some flag, for example is_symphaty INT (then 1 will mean likes, 0 will mean dislike)
然后查询本身
SELECT pm.name AS male_name, pf.name AS female_name
FROM person pm
CROSS JOIN person pf
WHERE pm.sex = 'M' AND pf.sex = 'F'
NOT EXISTS (
SELECT * FROM person_symphaty ps WHERE ps.person_id = pm.id AND ps.symphaty_person_id = pf.id
)
可能会出现错误,因为我根本没有测试这些查询。