复杂的 MySQL COUNT 查询
晚上好,各位,
我有一个复杂的 MySQL COUNT 查询,我正在尝试执行,并且正在寻找最好的方法来执行它。
- 在我们的系统中,我们有参考文献。每个参考可以有许多(或没有)收入来源,每个收入来源都可以验证或不验证(
状态
)。我们有一个参考表和一个收入表 - 收入表中的每一行都指向带有reference_id
的参考 - 在我们的“等待”页面(显示每个尚未验证的收入的屏幕),我们将其按参考分组。例如,您可能会看到约翰·史密斯先生有 3 个收入来源。
- 我们希望它在每行旁边显示类似“2 of 3 Validated”的内容
- 我的问题是编写解决这个问题的查询!
我一直在尝试做的是,使用 PHP 和 MySQL 的组合来弥补 SQL(或我的知识)不足的差距:
首先,选择与以下相关的收入数量的 COUNT
每个引用:
SELECT `reference_id`, COUNT(status) AS status_count
FROM (`income`)
WHERE `income`.`status` = 0
GROUP BY `reference_id`
接下来,使用 PHP 生成 WHERE IN
子句后,继续 COUNT
确认这些引用的数量:
SELECT `reference_id`, COUNT(status) AS status_count
FROM (`income`)
WHERE `reference_id` IN ('8469', '78969', '126613', ..... etc
AND status = 1
GROUP BY `reference_id`
但这不起作用。它返回 0 行。
有什么办法可以实现我所追求的目标吗?
谢谢!
Evening folks,
I have a complex MySQL COUNT query I am trying to perform and am looking for the best way to do it.
- In our system, we have References. Each Reference can have many (or no) Income Sources, each of which can be validated or not (
status
). We have a Reference table and an Income table - each row in the Income table points back to Reference withreference_id
- On our 'Awaiting' page (the screen that shows each Income that is yet to be validated), we show it grouped by Reference. So you may, for example, see Mr John Smith has 3 Income Sources.
- We want it to show something like "2 of 3 Validated" beside each row
- My problem is writing the query that figures this out!
What I have been trying to do is this, using a combination of PHP and MySQL to bridge the gap where SQL (or my knowledge) falls short:
First, select a COUNT
of the number of incomes associated with each reference:
SELECT `reference_id`, COUNT(status) AS status_count
FROM (`income`)
WHERE `income`.`status` = 0
GROUP BY `reference_id`
Next, having used PHP to generate a WHERE IN
clause, proceed to COUNT
the number of confirmed references from these:
SELECT `reference_id`, COUNT(status) AS status_count
FROM (`income`)
WHERE `reference_id` IN ('8469', '78969', '126613', ..... etc
AND status = 1
GROUP BY `reference_id`
However this doesn't work. It returns 0 rows.
Any way to achieve what I'm after?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 MySQL 中,您可以对布尔表达式进行 SUM() 来获取该表达式为 true 的行数。您可以这样做,因为 MySQL 将 true 视为整数 1,将 false 视为整数 0。
In MySQL, you can SUM() on a boolean expression to get a count of the rows where that expression is true. You can do this because MySQL treats true as the integer 1 and false as the integer 0.