LEFT JOIN table 查找不匹配的行,相同 table
LEFT JOIN table to find non matching rows, same table
我有一个 table
看起来像这样:
id int primary key
uniqueID string --not uniquely indexed
foreignKeyID int --foreignKey to another table
我想在此 table 中找到外键 1 存在但外键 2 不存在的所有 uniqueIds
我以为我可以做这样的事情:
SELECT * FROM table t1
LEFT JOIN table t2
ON t1.uniqueID = t2.uniqueID
WHERE
t1.foreignKeyID = 1
AND t2.uniqueID IS NULL
然而,这从来没有给我结果。我可以让它与 NOT IN
子查询一起工作,但这是一个非常大的 table,所以我怀疑使用连接的解决方案会更快。
正在寻找构建此查询的最佳方式。
这是一个示例数据集和 SQL Fiddle 以及我正在尝试转换为 LEFT JOIN
:[=21= 的工作 NOT IN
查询示例]
CREATE TABLE `table` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`uniqueID` varchar(255),
`foreignKeyID` int(5) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
INSERT INTO `table` (uniqueID, foreignKeyID) VALUES ('aaa', 1), ('bbb', 1);
http://sqlfiddle.com/#!9/48a3f3/4 和一个不工作的 LEFT JOIN
我认为是等价的。
谢谢!
试试这个,如果正确理解问题,似乎可以工作:
SELECT *
FROM `table` t
LEFT JOIN `table` tt ON tt.uniqueID = t.uniqueID AND tt.foreignKeyID <> 1
WHERE t.foreignKeyID = 1 AND tt.id IS NULL;
我有一个 table
看起来像这样:
id int primary key
uniqueID string --not uniquely indexed
foreignKeyID int --foreignKey to another table
我想在此 table 中找到外键 1 存在但外键 2 不存在的所有 uniqueIds
我以为我可以做这样的事情:
SELECT * FROM table t1
LEFT JOIN table t2
ON t1.uniqueID = t2.uniqueID
WHERE
t1.foreignKeyID = 1
AND t2.uniqueID IS NULL
然而,这从来没有给我结果。我可以让它与 NOT IN
子查询一起工作,但这是一个非常大的 table,所以我怀疑使用连接的解决方案会更快。
正在寻找构建此查询的最佳方式。
这是一个示例数据集和 SQL Fiddle 以及我正在尝试转换为 LEFT JOIN
:[=21= 的工作 NOT IN
查询示例]
CREATE TABLE `table` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`uniqueID` varchar(255),
`foreignKeyID` int(5) unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
INSERT INTO `table` (uniqueID, foreignKeyID) VALUES ('aaa', 1), ('bbb', 1);
http://sqlfiddle.com/#!9/48a3f3/4 和一个不工作的 LEFT JOIN
我认为是等价的。
谢谢!
试试这个,如果正确理解问题,似乎可以工作:
SELECT *
FROM `table` t
LEFT JOIN `table` tt ON tt.uniqueID = t.uniqueID AND tt.foreignKeyID <> 1
WHERE t.foreignKeyID = 1 AND tt.id IS NULL;