mysql选择问题,多表

时间:2013-02-27 03:21:41

标签: mysql sql select join

虽然我之前曾问过类似的问题,但我试图对它应用相同的技术,它只是不能正常工作,错误和各种各样的观点。

我为此创建了一个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');

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

运行代码时,会产生错误:

  

专栏' shop_id'在字段列表中是不明确的:SELECT animal_id,   animal_name,animal_type_name,shelter_name,shop_id,location_name   来自动物的INNER JOIN避难所s on s.shop_id = a.shop_id INNER   JOIN location l ON l.location_id = s.location_id INNER JOIN   ON at.animal_type_id = a.animal_type_id

中的animal_types

从错误:您的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