我一直在用砖墙砸我的头试图让这个工作,我不知道为什么不这样做。
我使用my_field连接表A和B.然后我运行一个子查询来从表B 获取my_field,其中complete = 1 。这就是我想用来查询表C和D
的内容这是我当前的查询
SELECT
table_A.*,
table_B.*,
table_C.*,
table_D.*
FROM table_A
INNER JOIN table_B ON
table_A.my_field = table_B.my_field
LEFT JOIN (SELECT my_field FROM table_B WHERE complete ='1') test ON
table_B.my_field = test.my_field
RIGHT JOIN table_C ON
test.my_field = table_C.my_field
INNER JOIN table_D ON
table_C.my_field = table_D.my_field
这是当前查询的输出
table_A.field1 | table_A.field2 | table_B.field1 | table_B.field2 | table_C.field1 | table_C.field2 | table_D.field1 | table_D.field2 | test.complete
=============================================================================================================================================================================
something | something | something | something | something | something | something | something | 1
null | null | null | null | something | something | something | something | 0
这就是我想要的
table_A.field1 | table_A.field2 | table_B.field1 | table_B.field2 | table_C.field1 | table_C.field2 | table_D.field1 | table_D.field2 | test.complete
=============================================================================================================================================================================
something | something | something | something | something | something | something | something | 1
something | something | something | something | null | null | null | null | 0
更新:
这是表格结构。我删除了没有链接到任何其他表的列
CREATE TABLE IF NOT EXISTS `table_A` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`code` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code` (`code`)
);
CREATE TABLE IF NOT EXISTS `table_B` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`code` varchar(255) NOT NULL,
`complete` enum('0','1') NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS `table_C` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`code` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code` (`code`)
);
CREATE TABLE IF NOT EXISTS `table_D` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`code` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
);
答案 0 :(得分:1)
为什么不摆脱左联盟?这使得阅读更容易。
SELECT
table_A.*,
table_B.*,
table_C.*,
table_D.*
FROM table_A
INNER JOIN table_B ON
table_A.my_field = table_B.my_field
LEFT JOIN table_C ON
table_B.my_field = table_C.my_field and table_B.complete ='1'
LEFT JOIN table_D ON
table_C.my_field = table_D.my_field