我有一个联系人表格,例如
Contacts
number (Primary key)
name (name of the contact)
Messages
id (primary key)
number (reciever or sender's phone number)
type (sent or recieved)
text (message body)
date (timestamp)
我想要的是,当我查询消息并按电话号码对它们进行分组以进行对话时,我想更改消息表中的电话号码以更改联系人表中联系人的姓名(如果存在) ,如果不存在,请将电话号码保留为电话号码,因为有未知号码也可以发短信。 PS:我在谷歌上搜索了很多以找到解决方案,但没有找到。
例如,
Contacts table contain
id name
1 a
2 b
Messages Contain
id number type text date
1 1 sent haha 123456
2 3 recieved hi 123459
现在结果应该是
number type text date
a sent haha 123456
3 received hi 123459
最佳答案
您需要在Messages
表和Contacts
表之间使用LEFT JOIN
。
SELECT
COALESCE(c.name,m.id) AS number,
m.type,
m.text,
m.date
FROM messages m
LEFT JOIN contacts C ON m.number = C.id;
<小时/>
注意:
MySQL COALESCE() 函数返回列表中的第一个非 NULL 值,如果没有非 NULL 值,则返回 NULL。
mysql> SELECT COALESCE(NULL, 2, 3);
+----------------------+
| COALESCE(NULL, 2, 3) |
+----------------------+
| 2 |
+----------------------+
1 row in set (0.02 sec)
mysql> SELECT COALESCE(NULL, NULL, NULL);
+----------------------------+
| COALESCE(NULL, NULL, NULL) |
+----------------------------+
| NULL |
+----------------------------+
1 row in set (0.00 sec)
关于php - 更改电话号码和联系人姓名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39815546/