我有这样的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
答案 0 :(得分:0)
可能有cash_in
和in
的错字。
$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_in
和cash_out
条目,因为连接条件仅检查总是匹配的note1.noteDate = note2.noteDate
。
可能在where
条件内添加on
条件,看看是否正是您想要的。