使用JOIN sql从2个不同的表中获取数据。笨

时间:2009-07-24 18:36:42

标签: sql codeigniter join

我使用codeigniter,我需要从2个不同的表中获取数据。现在它只返回works_image表中的数据。如何从两个表中获取数据?

非常感谢!!

$this->db->select('works_image.*', 'works.*');
$this->db->from('works_image', 'works');
$this->db->join('works', 'works.id = works_image.id_work');
$result = $this->db->get();

foreach ($result->result() as $row) {
    echo " # " . $row->id . " - " . $row->thumb . " - " . $row->wname . "
"; }

3 个答案:

答案 0 :(得分:4)

只要您执行SELECT *Why is this a bad idea?),就不需要指定调用select()的表格。它默认会选择所有字段。

$this->db->from('works_image', 'works');
$this->db->join('works', 'works.id = works_image.id_work');
$result = $this->db->get();

应该可以正常工作。

相反,你真正应该做的是确切地指定你需要的字段:

$this->db->select('works_image.id, works_image.name, works_image.id_work, works.id, works.name'); // (or whichever fields you're interested in)
$this->db->from('works_image', 'works');
$this->db->join('works', 'works.id = works_image.id_work');
$result = $this->db->get();

通过这种方式,您可以确保(a)您没有从数据库中提取不必要的数据,以及(b)在您修改数据库架构时,您的代码不会中断。

答案 1 :(得分:1)

这篇文章应该回答你的问题:http://www.whypad.com/posts/codeigniter-activerecord-join-tip/178/

简而言之,您需要从

重写select语句
$this->db->select('works_image.*', 'works.*');

到此:

$this->db->select('works_image.*, works.*');

请注意,这是Google针对“CodeIgniter加入”的第一个结果。首先尝试使用Google搜索您的问题。你可以经常给自己一个更快的答案:)

答案 2 :(得分:0)

你应该写下面的代码

$this->db->select('works_image.*', 'works.*');
$this->db->from('works_image');
$this->db->join('works', 'works.id = works_image.id_work');
$result = $this->db->get();

foreach ($result->result() as $row) {
echo " # " . $row->id . " - " . $row->thumb . " - " . $row->wname . "
";
} 

我认为你得到了你的结果