如何将以下内容转换为正确的codeigniter活动记录语法。
function postsInterest($user_id)
{
$query = $this->db->query("
SELECT b.*,
users.country,
users.company,
users.pic_small,
users.subscription,
COUNT(leads.user_id) AS leads
FROM trading AS u
INNER JOIN trading AS b
LEFT JOIN users ON users.user_id = b.user_id
LEFT JOIN leads ON b.trade_id = leads.trade_id
WHERE u.stock_type = b.stock_type
AND u.buying_selling != b.buying_selling
AND u.bond = b.bond
AND u.user_id = $user_id
AND b.user_id != $user_id
AND u.timestamp > unix_timestamp(now() - interval 120 DAY)
AND b.timestamp > unix_timestamp(now() - interval 120 DAY)
GROUP BY b.trade_id
ORDER BY b.timestamp DESC");
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
}
以上内容适用于快速修复,但希望将其与其他查询保持内联,以便我可以使用分页库。
答案 0 :(得分:1)
我不确定查询是否会起作用。 INNER JOIN trading AS b
但是没有指定连接条件,尽管所需的谓词位于where子句中。这些是“加入条件”
WHERE u.stock_type = b.stock_type
AND u.buying_selling != b.buying_selling
AND u.bond = b.bond
在每一个中,一侧有一个表u
,另一个表b
。使用显式连接语法时,应将此类的所有谓词移动到连接上。
我相信您将更成功地将其转换为codeigniter语法:
SELECT
b.*
, users.country
, users.company
, users.pic_small
, users.subscription
, COUNT(leads.user_id) AS leads
FROM trading AS u
INNER JOIN trading AS b ON u.stock_type = b.stock_type
AND u.buying_selling != b.buying_selling
AND u.bond = b.bond
LEFT JOIN users ON users.user_id = b.user_id
LEFT JOIN leads ON b.trade_id = leads.trade_id
WHERE u.user_id = @user_id
AND b.user_id != @user_id
AND u.timestamp > unix_timestamp(now() - interval 120 DAY)
AND b.timestamp > unix_timestamp(now() - interval 120 DAY)
GROUP BY
b.trade_id
ORDER BY
b.timestamp DESC
请注意,您依赖于MySQL对分组查询的非标准支持,并且如果sql_mode更改为only_full_group_by,则我们的查询将失败。在MySQL 5.7.2中,默认值为only_full_group_by