mysql - 在 codeigniter 查询生成器中使用 union,并在虚拟 mysql 列中进行过滤

标签 mysql database codeigniter activerecord query-builder

在我的项目中,我使用数据表插件进行服务器端处理。它工作正常,直到我执行搜索或排序(排序)操作,因为它需要事件记录才能执行此操作。

我的场景是,我有一个账户表、收入表和付款表,我想查看收入和付款表的所有数据,这就是为什么我需要一个联合。我的查询如下---

SELECT 'Income' as source, fld_type, fld_amount, ta.fld_account as account,  fld_date, tbl_revenue.fld_description as fld_traninfo, tbl_revenue.fld_created as created
        FROM tbl_revenue JOIN tbl_accounts as ta on tbl_revenue.fld_account_id = ta.fld_id
UNION
SELECT 'Expense' as source, fld_type, fld_amount, tae.fld_account, fld_date, tbl_payment.fld_description as fld_traninfo, tbl_payment.fld_created as created
        FROM tbl_payment JOIN tbl_accounts as tae on tbl_payment.fld_account_id = tae.fld_id

有什么方法可以在此查询中使用查询生成器吗?

第二个问题,您可以看到我创建了一个名为“source”的虚拟列,我想使用 where 子句过滤此列并附加此查询,如下所示

WHERE source like "%a%" limit(10,0)

但这返回我没有任何列名“source”,如何过滤此列?

感谢任何帮助。

最佳答案

有一种方法可以做到这一点,但它有点hacky,因为如果您没有自己指定,codeigniter 的查询构建器会向查询添加一个自动 SELECT 语句

为了获得您想要的结果,您必须将 select 语句拆分为 2 个查询,并向该查询添加 where 子句

类似的东西应该有效:

$strQuery1 = $this->db
    ->select('income as source, fld_type, fld_amount, ta.fld_account as account,  fld_date, tbl_revenue.fld_description as fld_traninfo, tbl_revenue.fld_created as created')
    ->from('tbl_revenue')
    ->join('tbl_accounts as ta', 'tbl_revenue.fld_account_id = ta.fld_id')
    ->get_compiled_select();

$strQuery2 = $this->db
    ->select('Expense as source, fld_type, fld_amount, ta.fld_account as account,  fld_date, tbl_revenue.fld_description as fld_traninfo, tbl_revenue.fld_created as created')
    ->from('tbl_payment')
    ->join('tbl_accounts as ta', 'tbl_revenue.fld_account_id = ta.fld_id')
    ->get_compiled_select();

$strWhere = substr($this->db->like('source', 'a', 'both')->get_compiled_select(), 8);

$query = $this->db->query($strQuery1.' UNION '.$strQuery2.$strWhere);

关于mysql - 在 codeigniter 查询生成器中使用 union,并在虚拟 mysql 列中进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49103916/

相关文章:

PHP/SQL PDO 准备/执行插入语句不起作用

sql - 数据库字段定义

php - 多个where条件codeigniter事件记录

php - 从sql表中查询数据,其中引用在另一个表中

mysql - 多连接 MYSQL VB.NET RowCount

php - CodeIgniter:无法使用提供的连接到您的数据库服务器

PHP多维数组查找特定维度中的重复项

MySQL 查询返回重复行

mysql - 如何提高 ORDER BY ... LIMIT ... 查询性能?

mysql - 如何不选择另一个表中存在的值