gpt4 book ai didi

php - 在 codeigniter 中转换复杂的 JOIN 查询

转载 作者:可可西里 更新时间:2023-11-01 07:56:40 26 4
gpt4 key购买 nike

我正在将我现有的网站转换为 CI,几天来我一直在尝试将此查询转换为 CI 友好的代码:

$result = mysql_query("
SELECT t1.mnumber, t1.mcontent, t1.mcontact
FROM sms t1
JOIN (
SELECT mContent,mcontact, mnumber, MAX(mID) mID
FROM sms
GROUP BY mContact
) t2 ON t1.mcontact = t2.mcontact AND t1.mid = t2.mid
GROUP BY t1.mContact
ORDER BY t1.mid DESC
");

但无论我怎么尝试,我都无法在 CI 上得到正确的结果。

我希望你们能帮帮我!


我得到的最接近结果是在我使用子查询 hack 时。然而,出于沮丧,我删除了代码块并继续尝试。

我决定使用平面查询,就像上面发布的那样。这几乎给了我结果。

$query = $this->db->query("SELECT t1.mnumber, t1.mcontent, t1.mcontact FROM sms t1JOIN (SELECT mContent,mcontact, mnumber, MAX(mID) mID FROM sms GROUP BY mContact) t2ON t1.mcontact = t2.mcontact AND t1.mid = t2.mid GROUP BY t1.mContact ORDER BY t1.mid DESC"); $contacts = array();//Add data to our arrayforeach($query->result() as $row){     echo $row->mNumber;}return $contacts;

但是,在我看来,我收到通知“消息:未定义的属性:stdClass::$mNumber”

所以仍然没有结果,而且我更喜欢CI查询方法。

最佳答案

你可以像这样在codeigniter中使用它

$query = "  SELECT t1.mnumber, t1.mcontent, t1.mcontact
FROM sms t1
JOIN (
SELECT mContent,mcontact, mnumber, MAX(mID) mID
FROM sms
GROUP BY mContact
) t2 ON t1.mcontact = t2.mcontact AND t1.mid = t2.mid
GROUP BY t1.mContact
ORDER BY t1.mid DESC";
$result = $this->db->query($query);
return $result->result();

第二种方法

为此,您可以使用 codeigniter 的子查询方式来执行此操作将不得不破解codeigniter。像这样。转到系统/数据库/DB_active_rec.php从这些函数中删除 public 或 protected 关键字

public function _compile_select($select_override = FALSE)
public function _reset_select()

现在可用的子查询写入现在这是您的带有事件记录的查询

$select =   array(
'mContent',
'mcontact',
'mnumber',
'MAX(mID) mID'
);
$this->db->select($select);
$this->db->from('sms');
$this->db->group_by('mContact');
$subquery = $this->db->_compile_select(); // get the query string

$this->db->_reset_select(); // reset so it can newly form the query

unset($select);
$select = array(
't1.mnumber',
't1.mcontent',
't1.mcontact'
);
$this->db->select($select);
$this->db->join('',"($subquery)");
$this->db->from('sms t1');
$this->db->group_by('t1.mContact');
$this->db->order_by('t1.mid','DESC');
$result = $this->db->get();
return $result->result();

然后事情就完成了。干杯!!!注意:在使用子查询时你必须使用

$this->db->from('myTable')

代替

$this->db->get('myTable')

运行查询。

关于php - 在 codeigniter 中转换复杂的 JOIN 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16107730/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com