2013-02-27 67 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