Mysql

MYSQL:當外鍵為NULL時顯示NULL值

  • January 13, 2019

我在 MYSQL 中有以下數據庫結構:

CREATE TABLE xs_bugtracking ( 
                   `id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, 
                   `product` VARCHAR(64) NOT NULL,
                   `title` VARCHAR(64) NOT NULL,
                   `status` VARCHAR(8) NOT NULL,
                   `descr` VARCHAR(1024) NOT NULL,
                   `assignee` INT(11),
                   `reported_by` INT(11) NOT NULL,
                   `importance` VARCHAR(8),
                   `create_date` INT(11) NOT NULL,
                   `modify_date` INT(11) NOT NULL
                   );

wordpress db同一張表的欄位assignee和外鍵: wp_usersreported_by

現在我想通過以下 SELECT 查詢獲取所有元素:

SELECT xs_bugtracking.id, product, xs_bugtracking.title AS title, status, xs_bugtracking.descr AS descr,
           assignee_tbl.user_nicename AS assignee,reported_tbl.user_nicename AS reported_by,importance,
           FROM_UNIXTIME(create_date) AS 'create_date', FROM_UNIXTIME(create_date) AS 'modify_date' 
           FROM xs_bugtracking, xs_products, wp_users AS assignee_tbl,
           wp_users AS reported_tbl WHERE 
           xs_products.name=product AND xs_products.lang='en' AND
           (xs_bugtracking.assignee=assignee_tbl.ID OR ISNULL(xs_bugtracking.assignee)) AND
           xs_bugtracking.reported_by=reported_tbl.ID

現在,當您有一行assignee等於時,問題就來了NULL,實際上結果表在值為 時乘以行,因為從akaNULL失去了 JOIN 。wp_users``assignee_tbl

有一種方法可以顯示assignee_tbl.user_nicename什麼時候assignee不是NULLNULL什麼時候assigneeNULL

如果你想查看完整的原始碼

提前致謝!

我建議您使用 SQL92 中引入的 ANSI 連接。如果您使用 LEFT JOIN,我認為您可以實現您想要的:

SELECT xs_bugtracking.id, product
    , xs_bugtracking.title AS title
    , status
    , xs_bugtracking.descr AS descr
    , assignee_tbl.user_nicename AS assignee
    , reported_tbl.user_nicename AS reported_by
    , importance
    , FROM_UNIXTIME(create_date) AS 'create_date'
    , FROM_UNIXTIME(create_date) AS 'modify_date' 
FROM xs_bugtracking
JOIN xs_products
   ON xs_bugtracking.product = xs_products.name 
LEFT JOIN wp_users AS assignee_tbl
   ON xs_bugtracking.assignee = assignee_tbl.ID
JOIN wp_users AS reported_tbl 
   ON xs_bugtracking.reported_by=reported_tbl.ID 
WHERE xs_products.lang='en' 

引用自:https://dba.stackexchange.com/questions/227039