2016-04-06 43 views
0

我已經添加了這個簡單的例子,以顯示我遇到的問題。說這是我的數據庫foo。MySQL如何跨多列進行INNER JOIN,即使某些列爲空。

SELECT 
    `people`.`id` 
    , `people`.`name` 
    , `places`.`place_type` 
    , `places`.`aread` 
    , `family`.`family_count` 
    , `income`.`income_value` 
    , `income`.`average` 
    , `employment`.`address` 
    , `employment`.`duration` 
FROM 
    `people` 
    INNER JOIN `places` 
     ON (`people`.`id` = `places`.`id`) 
    INNER JOIN `family` 
     ON (`people`.`id` = `family`.`id`) 
    INNER JOIN `income` 
     ON (`people`.`id` = `income`.`id`) 
    INNER JOIN `employment` 
     ON (`people`.`id` = `employment`.`id`) WHERE `people`.`full_name` = ? LIMIT 1 

現在,這裏的問題是,我得到空值,如果people.id沒有在其他列中的每個ID匹配。這是因爲並不是所有的身份證號碼都在地方,家庭,收入......列中找到。 所以,我想知道怎麼總是返回從people.id一個值,即使例如people.id不一樣的說.. income.id

+0

不確定你想要什麼?如果所有表中都有相同的people.id條目,那麼是否只想返回一行? – Remy

+1

如果我理解正確,你想從'人桌'的所有記錄嗎?如果是的話,請使用'LEFT JOIN' –

回答

2

只要改變你的加入到LEFT JOINLEFT表,只有匹配從RIGHT表返回所有記錄:

SELECT 
    `people`.`id` 
    , `people`.`name` 
    , `places`.`place_type` 
    , `places`.`aread` 
    , `family`.`family_count` 
    , `income`.`income_value` 
    , `income`.`average` 
    , `employment`.`address` 
    , `employment`.`duration` 
FROM  
    `people` 
    LEFT JOIN `places` 
     ON (`people`.`id` = `places`.`id`) 
    LEFT JOIN `family` 
     ON (`people`.`id` = `family`.`id`) 
    LEFT JOIN `income` 
     ON (`people`.`id` = `income`.`id`) 
    LEFT JOIN `employment` 
     ON (`people`.`id` = `employment`.`id`) WHERE `people`.`full_name` = ? LIMIT 1 

編輯:如果你想知道哪些表沒沒有匹配,只搜索空值。當離開加入時,與條件不匹配的表將在其列選擇上得到NULL值。

+0

謝謝,有沒有什麼辦法可以知道例如結果中缺少哪一列?我的意思是,如果缺少家人,有沒有辦法知道像'LEFT JOIN family'這樣的操作,並且在'empty'($ result ['f'])或類似的結果中可以做到這一點? – ANW

+0

@ANW缺少的將被選爲NULL值!因此,每個從這些表中爲空的列(如果其默認情況下不爲空)意味着此表丟失。 – sagi

1

更換LEFT JOININNER JOIN

SELECT 
    `people`.`id` 
    , `people`.`name` 
    , `places`.`place_type` 
    , `places`.`aread` 
    , `family`.`family_count` 
    , `income`.`income_value` 
    , `income`.`average` 
    , `employment`.`address` 
    , `employment`.`duration` 
FROM 
    `people` 
    LEFT JOIN `places` 
     ON (`people`.`id` = `places`.`id`) 
    LEFT JOIN `family` 
     ON (`people`.`id` = `family`.`id`) 
    LEFT JOIN `income` 
     ON (`people`.`id` = `income`.`id`) 
    LEFT JOIN `employment` 
     ON (`people`.`id` = `employment`.`id`) WHERE `people`.`full_name` = ? LIMIT 1 
+0

謝謝,有沒有什麼辦法可以知道結果中缺少哪一列?我的意思是,如果缺少家人,有沒有辦法知道像'LEFT JOIN family'這樣的操作,並且在'empty'($ result ['f'])或類似的結果中可以做到這一點? – ANW