2013-02-27 82 views
1

雖然我之前提出過類似的問題,但我試圖將相同的技術應用於它,但它並不像它應該的那樣工作,並且出現錯誤和各種各樣的問題。mysql select issue,multi tables

我爲此創建了一個sqlfiddle; http://sqlfiddle.com/#!2/b1a29

我試圖創建一個select函數,它將返回animal_id,animal_name,animal_type_name,shelter_name,animal_type_id和location_name。

我試圖用下面的代碼有一個很好,但很明顯,我失去了一些東西;

$query = $this->db->query('SELECT animal_id, animal_name, animal_type_name, shelter_name, shop_id, location_name 
           FROM animals a 
           INNER JOIN shelter s ON s.shop_id = a.shop_id 
           INNER JOIN location l ON l.location_id = s.location_id 
           INNER JOIN animal_types at ON at.animal_type_id = a.animal_type_id'); 
+0

與使用內部聯接每個表都必須包含一個coorsponding值。你確定所有的動物都有避難所,地點和類型嗎? – xQbert 2013-02-27 03:24:49

+0

您已關閉:http://sqlfiddle.com/#!2/b1a29/7 – sgeddes 2013-02-27 03:25:11

回答

2

問題是,您正在選擇不明確的列名或存在於多個表上的列名。在這種情況下,它是shop_id。爲了執行查詢好了,你需要指定列shop_id應該來自,

SELECT animal_id, animal_name, animal_type_name, 
     shelter_name, s.shop_id, location_name 
FROM animals a 
INNER JOIN shelter s ON s.shop_id = a.shop_id 
INNER JOIN location l ON l.location_id = s.location_id 
INNER JOIN animal_types at ON at.animal_type_id = a.animal_type_id 
+0

謝謝JW!一個快速谷歌搜索告訴我,這是因爲它列出了兩次,但這個例子似乎把「tablename.collum」,所以當我厭倦了做shelter.shop_id,它錯了。現在有道理,再次感謝! – user1725794 2013-02-27 03:27:16

+0

你的表格彼此之間有什麼關係? – 2013-02-27 03:29:30

+0

@ user1725794不客氣':D' – 2013-02-27 03:30:07

0

當我運行你的代碼,它產生錯誤:

Column 'shop_id' in field list is ambiguous: SELECT animal_id, animal_name, animal_type_name, shelter_name, shop_id, location_name FROM animals a INNER JOIN shelter s ON s.shop_id = a.shop_id INNER JOIN location l ON l.location_id = s.location_id INNER JOIN animal_types at ON at.animal_type_id = a.animal_type_id

出錯:您的shop_id列屬於更多的表,因此您必須使用表名/表別名進行限定。

查詢改成這樣:

SELECT animal_id, animal_name, animal_type_name, shelter_name, s.shop_id, location_name 
           FROM animals a 
           INNER JOIN shelter s ON s.shop_id = a.shop_id 
           INNER JOIN location l ON l.location_id = s.location_id 
           INNER JOIN animal_types at ON at.animal_type_id = a.animal_type_id