在具有可接受的NULL值的多个表上执行JOIN

时间:2014-04-30 01:08:17

标签: php mysql sql

我有多个表并尝试执行JOIN查询。 以下代码可以正常工作,除非WHERE子句中的一列是NULL - 我根本不会得到任何结果。

我是否需要使用FULL OUTER JOIN?

请帮忙。

SELECT  tickets.*,

    tickets_statuses.name AS statusname,

    tickets_priorities.name AS priorityname,

    clients.name AS clientname,

    clients_locations.name AS clientlocationname,
    clients_locations.address AS clientlocationaddress,
    clients_locations.address2 AS clientlocationaddress2,
    clients_locations.city AS clientlocationcity,
    clients_locations.state AS clientlocationstate,
    clients_locations.zip AS clientlocationzip,
    clients_locations.country AS clientlocationcountry,

    clients_contacts.prefix AS clientcontactprefix,
    clients_contacts.firstname AS clientcontactfirstname,
    clients_contacts.middlename AS clientcontactmiddlename,
    clients_contacts.lastname AS clientcontactlastname,
    clients_contacts.title AS clientcontacttitle

FROM    tickets, tickets_statuses, tickets_priorities, clients, clients_locations, clients_contacts
WHERE   tickets.id = '$ticket_id'
    AND tickets_statuses.id = tickets.statusid
    AND tickets_priorities.id = tickets.priorityid
    AND clients.id = tickets.clientid
    AND clients_locations.id = tickets.clientlocationid
    AND clients_contacts.id = tickets.clientcontactid

1 个答案:

答案 0 :(得分:3)

首先,我要说你想摆脱JOIN的旧语法并使用标准JOIN ... ON语法。

查询可能如下所示,但订单和加入可能会因您想要的列而异。以下假设您始终需要ticket中的某个项目,而其他任何项目可能存在,也可能不存在:

SELECT  tickets.*,
        tickets_statuses.name AS statusname,
        tickets_priorities.name AS priorityname,
        clients.name AS clientname,
        clients_locations.name AS clientlocationname,
        clients_locations.address AS clientlocationaddress,
        clients_locations.address2 AS clientlocationaddress2,
        clients_locations.city AS clientlocationcity,
        clients_locations.state AS clientlocationstate,
        clients_locations.zip AS clientlocationzip,
        clients_locations.country AS clientlocationcountry,
        clients_contacts.prefix AS clientcontactprefix,
        clients_contacts.firstname AS clientcontactfirstname,
        clients_contacts.middlename AS clientcontactmiddlename,
        clients_contacts.lastname AS clientcontactlastname,
        clients_contacts.title AS clientcontacttitle
FROM tickets
LEFT JOIN tickets_statuses
    ON tickets.statusid = tickets_statuses.id
LEFT JOIN tickets_priorities
    ON tickets.priorityid = tickets_priorities.id
LEFT JOIN clients
    ON tickets.clientid = clients.id
LEFT JOIN clients_locations
    ON tickets.clientlocationid = clients_locations.id
LEFT JOIN clients_contacts
    ON tickets.clientcontactid = clients_contacts.id
WHERE tickets.id = '$ticket_id'