MySQL where子句在Codeigniter中不起作用

时间:2019-03-14 10:21:32

标签: php mysql sql codeigniter

我有这样的MySQL查询:(我使用CodeIgniter)

$report = $this->db->query("
          SELECT c.categoryName,
            note1.*,
            ((SELECT SUM(noteAmount)
              FROM notes
              WHERE DATE_FORMAT(noteDate, '%d-%m-%Y') = DATE_FORMAT(note1.noteDate, '%d-%m-%Y') AND noteType = 'cash_in')
            -
            (SELECT SUM(noteAmount)
             FROM notes
             WHERE DATE_FORMAT(noteDate, '%d-%m-%Y') = DATE_FORMAT(note1.noteDate, '%d-%m-%Y') AND noteType = 'cash_out')) as trxCount
           FROM notes AS note1
           JOIN
             (SELECT noteDate
              FROM notes
              GROUP BY noteDate
              HAVING COUNT(noteDate) > 0)
            AS note2
              ON note1.noteDate = note2.noteDate
            JOIN category c
              ON c.categoryID = note1.categoryID
            WHERE note1.noteType = 'cash_in'
            ORDER BY note1.noteDate DESC
            LIMIT $start, $per_page
          ")->result();
  

请参阅WHERE子句:WHERE note1.noteType ='cash_in'

我只想获取现金数据,但是为什么我要获取所有数据? (包括套现及其他)。我的桌子上也有套现数据

笔记表:

  

noteID | noteTitle | noteDate | noteAmount | categoryID | noteType

类别表

  

categoryID | categoryName | parentID

3 个答案:

答案 0 :(得分:0)

可能有cash_inin的错字。

$report = $this->db->query("
          SELECT c.categoryName,
            note1.*,
            ((SELECT SUM(noteAmount)
              FROM notes
              WHERE DATE_FORMAT(noteDate, '%d-%m-%Y') = DATE_FORMAT(note1.noteDate, '%d-%m-%Y') AND noteType = 'in')
            -
            (SELECT SUM(noteAmount)
             FROM notes
             WHERE DATE_FORMAT(noteDate, '%d-%m-%Y') = DATE_FORMAT(note1.noteDate, '%d-%m-%Y') AND noteType = 'out')) as trxCount
           FROM notes AS note1
           JOIN
             (SELECT noteDate
              FROM notes
              GROUP BY noteDate
              HAVING COUNT(noteDate) > 0)
            AS note2
              ON note1.noteDate = note2.noteDate
            JOIN category c
              ON c.categoryID = note1.categoryID
            WHERE note1.noteType = 'in'
            ORDER BY note1.noteDate DESC
            LIMIT $start, $per_page
          ")->result();

答案 1 :(得分:0)

我相信您在where语句中缺少JOIN。如果这在ON元素上或在SELECT本身内进行,那么我相信这可以解决您的问题。

答案 2 :(得分:0)

查询

SELECT noteDate
          FROM notes
          GROUP BY noteDate
          HAVING COUNT(noteDate) > 0

将整个notes表选择为note2(包括cash_out条目),并且仅对note1.noteType = 'cash_in'处的条目进行过滤。这将同时提供cash_incash_out条目,因为连接条件仅检查总是匹配的note1.noteDate = note2.noteDate

可能在where条件内添加on条件,看看是否正是您想要的。