我有以下SQL查詢:從連接表僅當記錄存在
SELECT
Customers.CustomerName AS FullName,
Customers.Id AS CustomerId,
Customers.UserRoleId AS UserRoleId,
Customers.Email AS Email,
IFNULL(Customers.StudentId, '') AS CustomersStudentId,
IFNULL(Customers.MagentoId, '') AS MagentoId,
Sections.Id AS SectionId,
Sections.SectionNumber AS SectionNumber,
Sections.SectionName AS SectionName,
Courses.Id AS CourseId,
IFNULL(Courses.CourseName, '') AS CourseName,
IFNULL(Courses.CourseNumber,'') AS CourseNumber,
IFNULL(Courses.CourseDepartment, '') AS CourseDepartment,
IFNULL(Courses.Notes, '') AS CourseNotes,
IFNULL(Courses.Year, '') AS CourseYear,
IFNULL(Courses.CourseType, '') AS CourseType,
StudentsCourses.Id AS StudentsCoursesId,
IFNULL(StudentsCourses.StudentId, '') AS StudentsCoursesStudentId,
IFNULL(SiteProfile.StudentIdField, '') AS StudentIdField,
IFNULL(SiteProfile.SchoolEmailDomain, '') AS SchoolEmailDomain,
IFNULL(Orders.Id, '') AS OrderId
FROM Customers
LEFT JOIN StudentsCourses ON Customers.Id = StudentsCourses.CustomerId
LEFT JOIN Sections ON StudentsCourses.SectionId = Sections.Id
LEFT JOIN Courses ON StudentsCourses.CourseId = Courses.Id
LEFT JOIN BooksCourses ON Courses.Id = BooksCourses.CourseId
LEFT JOIN Products ON BooksCourses.ISBN = Products.ISBN
LEFT JOIN EbookVendors ON Products.EbookVendorId = EbookVendors.Id
LEFT JOIN Orders ON Customers.Id = Orders.CustomerId
LEFT JOIN SiteProfile ON Courses.SchoolCode = SiteProfile.SchoolCode
WHERE Customers.Id <> 10
AND StudentsCourses.SectionId IS NOT NULL
AND StudentsCourses.Delete <> 2
AND Courses.SchoolCode = '{$criteria["school_code"]}'
AND Courses.Year = {$criteria["year"]}
AND Courses.CourseType LIKE '{$criteria["term"]}'
記錄會一直存在於Customers
表。但是有時在任何其他連接的表中都不會有關聯的記錄。
如何修改查詢,以便在Customers
表中只有記錄時,附加的SELECT
和WHERE
子句不會中斷結果?
編輯:
當記錄只在Customers
存在,我希望這個紀錄,我想WHERE
條款,不屬於該Customers
表被忽略。
如果記錄存在於連接表中,我希望與該連接表有關的WHERE
子句起作用。
解釋得更好...請....只需要客戶和其他人表之間匹配的結果,或者您希望兩者都有....別名匹配結果和客戶與其他表之間不匹配的結果? – scaisEdge
更加清晰地編輯 – LXXIII
將不在客戶表中的記錄上的連接限制批評移至連接。例如:'LEFT JOIN StudentsCourses ON Customers.Id = StudentsCourses.CustomerId and StudentsCourses.SectionId IS NOT NULL AND StudentsCourses.Delete <> 2'限制應用於連接之前,因此在與studentsCourses的連接爲空時保留客戶記錄。在使用外部連接時,大部分時間都需要在連接之前執行。或者你必須像其他人在下面的答案中所做的那樣解決空值問題。 – xQbert