gpt4 book ai didi

php - 统计MySQL中不为空的字段个数

转载 作者:可可西里 更新时间:2023-11-01 07:24:13 24 4
gpt4 key购买 nike

我有一个用户数据库,他们可以在其中向其他用户(最多四个)发送消息,并且他们发送的消息的 ID 在他们的用户行中。

Name    | Email       | Msg1 | Msg2 | Msg3 | Msg4
--------+-------------+------+------+------+-----
Pez | me@me.com | 1 | 55 | 42 | 5
Steve | fake@me.com | 0 | 0 | 0 | 0
Leon | josh@me.com | 3 | 0 | 3 | 5

如何在 MySQL 查询中获取不为空或不等于 0 的消息行的数量,从而允许我按此进行排序?所以它会返回

Pez   | 4 Mesasges
Leon | 3 Messages
Steve | 0 Messages

我的想法是这样的:

order by count(!empty(msg1)+!empty(msg2)+!empty(msg3)+!empty(msg4)) 

最佳答案

normalized tables可以很简单

SELECT Count(*) FROM messages WHERE userid=47

但是用你的模式尝试类似的东西

SELECT
name,
(msg1<>0) + (msg2<>0) + (msg3<>0) + (msg4<>0) as cMessages
FROM
foo

编辑:Vincent Ramdhanie 的回答使用 if()不依赖于 MySQL 的行为来使用 0 作为 false 和 1 作为比较结果。我更愿意这样。

关于php - 统计MySQL中不为空的字段个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2514863/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com