我正在尝试为表“projects”上的搜索请求构建SQL查询。 搜索还与其他与项目表有关系的表有关。
我试过了:
SELECT projects.*
FROM projects
LEFT JOIN documents ON documents.projectID = projects.id
LEFT JOIN subdocuments ON documents.id = subdocuments.documentID
LEFT JOIN subdocuments_tags ON subdocuments.id = subdocuments_tags.subdocumentID
JOIN tags ON subdocuments_tags.tagID = tags.id
WHERE (projects.name LIKE "%Test%"
OR projects.clientName LIKE "%Test%"
OR projects.description LIKE "%Test%"
OR projects.defaultTags LIKE "%Test%"
OR documents.name LIKE "%Test%"
OR subdocuments.name LIKE "%Test%"
OR documents.description LIKE "%Test%"
OR subdocuments.description LIKE "%Test%"
OR tags.name LIKE "%Test%")
AND (projects.hidden = 0
OR projects.ownerID = 2
OR projects_users.userID = 2)
GROUP BY projects.id
ORDER BY projects.updateTime DESC;
问题在于,如果项目没有任何文档,即使没有WHERE子句,结果也总是为空。
答案 0 :(得分:1)
@MatBailie
进一步讨论......
DROP TABLE IF EXISTS i;
DROP TABLE IF EXISTS table_a;
CREATE TABLE ints (i INT NOT NULL PRIMARY KEY);
INSERT INTO ints VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9);
CREATE TABLE table_a (i INT NOT NULL,x CHAR(1) NOT NULL, PRIMARY KEY (i,x));
INSERT INTO table_a VALUES
(1,'a'),
(1,'b'),
(1,'c'),
(1,'d'),
(1,'e'),
(2,'a'),
(2,'b'),
(2,'c'),
(3,'a'),
(3,'b'),
(4,'a');
SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+
SELECT * FROM table_a;
+---+---+
| i | x |
+---+---+
| 1 | a |
| 1 | b |
| 1 | c |
| 1 | d |
| 1 | e |
| 2 | a |
| 2 | b |
| 2 | c |
| 3 | a |
| 3 | b |
| 4 | a |
+---+---+
SELECT m.* FROM ints m LEFT JOIN table_a n ON n.i = m.i WHERE n.x IN('c','d');
+---+
| i |
+---+
| 1 |
| 1 |
| 2 |
+---+
SELECT m.* FROM ints m JOIN table_a n ON n.i = m.i WHERE n.x IN('c','d');
+---+
| i |
+---+
| 1 |
| 1 |
| 2 |
+---+
答案 1 :(得分:0)
正如上面在注释中提到的那样,使用LEFT JOIN来包含项目表中的行,即使文档,子文档或标记表中没有匹配的行
SELECT projects.*
FROM projects
LEFT JOIN documents ON documents.projectID = projects.id
LEFT JOIN subdocuments ON documents.id = subdocuments.documentID
LEFT JOIN subdocuments_tags ON subdocuments.id = subdocuments_tags.subdocumentID
LEFT JOIN tags ON subdocuments_tags.tagID = tags.id
WHERE (projects.name LIKE "%Test%" OR projects.clientName LIKE "%Test%" OR projects.description LIKE "%Test%" OR projects.defaultTags LIKE "%Test%" OR documents.name LIKE "%Test%" OR subdocuments.name LIKE "%Test%" OR documents.description LIKE "%Test%" OR subdocuments.description LIKE "%Test%" OR tags.name LIKE "%Test%")
AND (projects.hidden = 0 OR projects.ownerID = 2 OR projects_users.userID = 2)
GROUP BY projects.id
ORDER BY projects.updateTime DESC;