CREATE TABLE players (
`userID` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`userID`));
CREATE TABLE opponents (
`userID` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`userID`));
CREATE TABLE relationship (
`user1_userID` INT NOT NULL,
`user2_userID` INT NOT NULL,
`blocked` TINYINT(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`user1_userID`, `user2_userID`));
INSERT INTO players (`name`)
VALUES ('alpha'), ('beta'), ('gamma'), ('delta');
INSERT INTO opponents (`name`)
VALUES ('alpha'), ('beta');
INSERT INTO relationship (`user1_userID`, `user2_userID`, `blocked`)
VALUES (1,2, 1), (1,3, 1), (1,4, 1), (2, 1, 1), (2,3, 1), (3,4, 1);
SELECT o.userID, o.name, ur.*
FROM opponents o
LEFT JOIN players p
ON (o.userID != p.userID)
LEFT JOIN relationship ur
ON ((ur.user1_userID = p.userID AND ur.user2_userID = o.userID) OR
(ur.user1_userID = o.userID AND ur.user2_userID = p.userID))
-- WHERE (ur.blocked != 1)
如果我不把WHERE
條件,我看到關係的列即測試版並未阻止三角洲NULL
一行。WHERE條件不相關的NULL,消除了空行的值
但是,當我取消註釋WHERE
條件,我期待只留下這一行。但它也被消除了。爲什麼會發生這種情況,以及如何正確編寫查詢?謝謝。
將where子句更改爲WHERE ur.blocked IS NULL –
使用(ur.blocked IS NULL)將是臨時解決方法。假設結果中有另一行,它的(ur.blocked是0)。我們希望所有具有NULL或0的行(基本上!= 1)。真正的問題是爲什麼(ur.blocked!= 1)消除了ur.blocked爲NULL的行? –
它是NULL的原因是因爲在連接中沒有匹配的行。使用WHERE ur.blocked IS NULL或者ur.blocked <> 1. –