我有2个表Users(名称TEXT)和“咖啡休息时间”(Person1 TEXT,Person2 TEXT)。
我需要编写一个联接,以返回给定用户没有喝咖啡休息时间的所有用户。
我正在尝试用右侧的IS NULL进行左连接。
数据库查询已完成,没有错误,但结果没有任何用户。我的SQL查询字符串有问题吗?
SQL:
WITH bilateral(p1, p2) AS (SELECT Person1 AS p1, Person2 AS p2 FROM "Coffee Breaks"
UNION ALL SELECT Person2 AS p1, Person1 AS p2 FROM "Coffee Breaks"
GROUP BY p1, p2)
SELECT * FROM Users u1, Users u2
LEFT JOIN bilateral bi ON u1.Name=bi.p1 AND u2.Name=bi.p2
WHERE bi.p1 IS NULL
样本数据:
Users
[
{
Name: "Casey"
},
{
Name: "Jake"
},
{
Name: "Mark"
},
{
Name: "Steve"
}
]
Coffee Breaks
[
{
Person1: "Steve",
Person2: "Casey"
}
]
服务器代码:
db.neverCoffeed = function(user) {
const sql = `WITH bilateral(p1, p2) AS (SELECT Person1 AS p1, Person2 AS p2 FROM "Coffee Breaks"
UNION ALL SELECT Person2 AS p1, Person1 AS p2 FROM "Coffee Breaks"
GROUP BY p1, p2)
SELECT * FROM Users u1, Users u2
LEFT JOIN bilateral bi ON u1.Name=bi.p1 AND u2.Name=bi.p2
WHERE bi.p1 IS NULL`;
return new Promise((resolve, reject) => {
this.run(sql, (err, users) => {
if (err) {
reject(err);
}
else {
console.log('users', users)
resolve(users);
}
});
});
};
答案 0 :(得分:1)
我期望这样的事情:
select u.*
from users u
where not exists (select 1
from coffeebreaks cb
where (cb.person1 = u.name and cb.person2 = ?) or
(cb.person2 = u.name and cb.person1 = ?)
);
?
是感兴趣的人的占位符。
答案 1 :(得分:0)
尝试更改此部分
SELECT * FROM Users u1, Users u2
LEFT JOIN bilateral bi ON u1.Name=bi.p1 AND u2.Name=bi.p2
WHERE bi.p1 IS NULL
收件人
(SELECT * FROM Users u1
LEFT JOIN bilateral bi ON u1.Name=bi.p1
WHERE bi.p1 IS NULL
UNION ALL
SELECT * FROM Users u2
LEFT JOIN bilateral bi ON u2.Name=bi.p2
WHERE bi.p2 IS NULL)