Php 检查表中的多行,如果行匹配,则将其计为1
我有一个名为Php 检查表中的多行,如果行匹配,则将其计为1,php,mysql,Php,Mysql,我有一个名为private\u messages的表,其结构如下: id message_from message_to 我正试图确定活动聊天室的数量,但该表存储了发送和接收的所有消息,因此,Alice在message\u from和message\u to中可能有许多行 假设我的private_messages表有4行: id message_from message_to 1 Alice conor 2 Alice
private\u messages
的表,其结构如下:
id message_from message_to
我正试图确定活动聊天室的数量,但该表存储了发送和接收的所有消息,因此,Alice
在message\u from
和message\u to
中可能有许多行
假设我的private_messages
表有4行:
id message_from message_to
1 Alice conor
2 Alice conor
3 connor Alice
4 Anderson conor
Alice和conor之间的对话应视为1
。因此,当我回音时,比如说$active\u conversations
,应该打印数字2
我假设这涉及一个数组?i、 e.$conversations=[]代码>。但除此之外,我不知道或不明白该怎么办
select count(id) from private_messages group by message_from,message_to
然后得到适当的结果如果您只想获得对话数,您可以使用类似的方法
SELECT COUNT(DISTINCT
CONCAT(
LEAST(message_from,message_to),
'->',
GREATEST(message_from,message_to)
)
) AS active_conversations
FROM private_messages;
输出:
active_conversations
2
FirstPerson SecondPerson
Alice conor
Anderson conor
如果您想获得对话的详细信息,可以使用此
SELECT DISTINCT
LEAST(message_from,message_to) as FirstPerson,
GREATEST(message_from,message_to) as SecondPerson
FROM private_messages;
输出:
active_conversations
2
FirstPerson SecondPerson
Alice conor
Anderson conor
其中一个问题是,'private_messages'中的元组('connor','Alice')和('Alice','connor')表示同一个会话/房间,无论您在数什么
一种方法是得到不同值的总数,然后除以2,但这似乎不是正确的方法。(我们可以设置一些边缘情况,其中返回的结果不是整数,或者小于活动房间的实际数量
id message_from message_to
-- ------------ ----------
1 Alice conor
2 Alice conor
3 conor Alice
4 Anderson conor
5 Cooper Alice
6 Dalton Allman
另一种方法是对元组中的值进行重新排序(将message_from和message_to交换),这些值与对话另一端的message_from和message_two匹配。例如,我们可以比较message_from和message_to,如果message_to比message_from“低”,则交换它们
例如,使用表达式返回m_one和m_two列中显示的值
id message_from message_to m_one t_two
-- ------------ ---------- ----- -----
1 Alice conor Alice conor
2 Alice conor Alice conor
3 conor Alice Alice conor
4 Anderson conor Anderson conor
5 Cooper Alice Alice Cooper
6 Allman Dalton Allman Dalton
然后我们可以计算(m_1,m_2)元组的不同值
第三种方法是丢弃message_from值高于message_to值的任何元组,去掉会话/房间的一侧。然后获得剩余的不同元组的计数。但同样,这可能会排除某些只有一个方向的消息的会话/房间
id message_from message_to m_one t_two
-- ------------ ---------- ----- -----
1 Alice conor Alice conor
2 Alice conor Alice conor
3 conor Alice Alice conor
4 Anderson conor Anderson conor
5 Cooper Alice (NULL) (NULL)
6 Allman Dalton Allman Dalton
(我们将讨论一个会话/房间的角落案例,其中message_from等于message_to。)
我们编写的SQL实际上取决于我们想要实现的算法
我们可以使用GROUP BY来折叠“匹配”行,并获得一个计数。或者我们可以使用count(DISTINCT foo)
来获得不同值的计数
如果我们选择需要“交换”值的算法,我们可以使用使用LEAST
和magest
函数的表达式。或者使用MySQL If()函数或CASE表达式
如果我们想从计数中排除行,我们可以在WHERE子句中包含一个谓词
所有这些都是可能的,并且有多种方法可以实现指定的结果。实际上,您的表应该还有一个名为conversation\u id
的列,或者在最坏的情况下,您需要为每个对话创建单独的表。您想要的输出是什么?此问题中的查询返回p中的行数计数rivate_来自对话/聊天室一侧的消息。对于问题中给出的示例数据,这将返回三行,不保证按任何特定顺序排列,值为2、1和1。这可能是一个“适当的结果”。但我不会将该结果描述为“活动聊天室的数量”。