2013-12-10 58 views
0

我有兩個表,其中一個包含3000個地區代碼(所以只是郵政編碼的前半部分),另一個表包含商店詳細信息,並且有一個名爲postcodes_covered的列,這些列都是例如: 商店1(AB1,AB2,AB3,AB4,AB5 ...),商店2(E15,E13,E14 ...)等等。我需要創建一個報告,其中包含3000個地區代碼以及如果來自表2的地區代碼包含在表1中則表示「是」的列或者如果該地區代碼未被覆蓋則表示「否」的列。我寫了一個很好的SQL查詢,但我需要在codeigniter中編寫它。我爲codeigniter編寫的代碼似乎不起作用,我不知道爲什麼?IF,Join和concat在codeigniter中不起作用

SQL查詢:

select bodyshops_postcode_allocation.area_code,if(postcodes_covered is null,"No","Yes") as "YeN" from bodyshops_postcode_allocation left join bodyshops on bodyshops.postcodes_covered like concat("%",bodyshops_postcode_allocation.area_code,"%"); 

笨:

function postcode_allocation() 
{ 
    $this->db->select('bodyshops_postcode_allocation.area_code as area_code') 
      ->select('IF(bodyshops.postcodes_covered is null, "No", "Yes") as match_found') 
      ->join('bodyshops', 'bodyshops.postcodes_covered LIKE CONCAT("%",bodyshops_postcode_allocation.area_code,"%")') 
      ->from('bodyshops_postcode_allocation'); 


    $this->load->dbutil(); 
    $data = $this->dbutil->csv_from_result($this->db->get('')); 

    $this->output->set_header("Content-type: application/vnd.ms-excel"); 
    $this->output->set_header("Content-disposition: attachment; filename=postcode_allocation.csv; size=".strlen($data)); 
    $this->output->set_output($data); 

} 

回答

0

當使用像這樣的笨SQL函數,你需要告訴它不要試圖逃跑查詢。

->select('IF(bodyshops.postcodes_covered is null, "No", "Yes") as match_found', FALSE) 

FALSE告訴笨離開字符串,如不設法反引號添加到它。它不知道如何在這種情況下添加它們,所以它會弄亂你的查詢。

P.S.你的加入需要是:

->join('bodyshops', 'bodyshops.postcodes_covered LIKE CONCAT("%",bodyshops_postcode_allocation.area_code,"%")', 'left') 

如果你想要一個LEFT JOIN,你需要告訴它。

P.P.S. $this->db->get('')應該只是$this->db->get()。不要傳遞一個空白的字符串。

+0

我做了一些像你說的修改,但是,我仍然收到錯誤。我是否正確地使用了like和concat運算符? @火箭Hazmat – user3009232

+0

@ user3009232:看起來對我來說很好。你遇到了什麼錯誤?如果你執行'echo $ this-> db-> last_query();'(在$ this-> db-> get()'調用之後),你會看到什麼? –

+0

我收到錯誤:1064「您的SQL語法有錯誤;請查看與您的MySQL服務器版本相對應的手冊,以便在LIKE CONCAT(」%「,bodyshops_postcode_allocation.area_code,」% 「)'在第3行」...當我把echo $ this-> db-> last_query();我犯了同樣的錯誤。 @Rocket Hazmat – user3009232