我正在使用php Codeigniter框架中的一个网站,并且在连接表时遇到问题。
这两张桌子是饭菜和餐馆,只是版本
meals: id, restaurant_id, price, etc.
restaurants: id, name, location, etc.
要进行查询,请使用以下代码:
$this->db->join('restaurants', 'restaurants.id = meals.restaurant_id');
$query = $this->db->get('meals');
返回与运行此相同的结果:
$query = $this->db->query('SELECT * FROM meals INNER JOIN restaurants ON restaurants.id = meals.restaurant_id');
问题是,当我以php数组或对象(由codeigniter DB类提供)的形式访问结果时,只返回一个id,餐馆ID,我需要用餐ID。我怎么能把它吐出来的饭?
答案 0 :(得分:2)
我对你当前的工具(php / codeigniter /等)没有经验,我假设问题出现了,因为两个表的“id”列都有相同的名称? (这通常不是问题......但是工具可能无法正确处理它?)对于SQL查询,区分具有相同名称的列的一种方法是在select语句中使用别名。这是一个例子:
select
m.id as meal_id,
m.price as meal_price,
r.id as restaurant_id,
r.name as restaurant_name,
r.location as restaurant_location
from meals as m
inner join restaurants as r on r.id = m.restaurant_id
答案 1 :(得分:1)
试试这个
SELECT t1.id as mid,t2.id as rid
FROM table_meals as t1
inner JOIN table_restaurant as t2 ON t2.id = t1.`restaurant_id`