MySQL使用中遇到的一个问题

来源:互联网 发布:pc端微信多开软件 编辑:程序博客网 时间:2024/05/16 13:03

这是一个设计的很烂的表,检索数据很费劲,最近学了内链接和外连接,用连接的方式要得到这题要的结果有点困难,试了能想到的好多查询方式,结果差强人意,最终换了个思路,用子查询解决了。

问题:有这么一个表,记录着用户发送的消息。现在要查询所有和id为5的用户有关的消息,并且从另外一张记录着用户姓名的表中检索出相关的用户姓名。比如如果from为5,则name列显示to所指向id的用户姓名,如果to为5,则name列显示from所指向id的用户姓名,如果没有对应的id,则name列显示null。

使用连接的方式的到的结果会没有null值,表中第一条符合的数据to所指向的用户id 88887 不存在,试了好几种连接方式,都把null值那一行丢了

最终解决方案(子查询):

mysql> select c.*,(select name from xb_user where xb_user.id = if(`from`=5,`to`,`from`)) as name from xb_chart as c where (`from` = 5 or `to` = 5);+----+------+-------+---------------------+------------+--------+--------+----------+----------+------+-------+---------------+| id | from | to    | content             | date       | belook | beback | isbackto | issystem | info | other | name          |+----+------+-------+---------------------+------------+--------+--------+----------+----------+------+-------+---------------+|  7 |    5 | 88887 | 消息测试1 | 2017-06-11 |      0 |      0 |        0 |        0 |      |       | NULL          ||  8 |    6 |     5 | test    | 2017-07-10 |      0 |      0 |        0 |        0 |      |       | 自科专家2     ||  9 |    5 |     6 | test2   | 2017-07-10 |      0 |      0 |        0 |        0 |      |       | 自科专家2     || 10 |    5 |     7 | test3   | 2017-07-10 |      0 |      0 |        0 |        0 |      |       | 主编          |+----+------+-------+---------------------+------------+--------+--------+----------+----------+------+-------+---------------+

更清楚的版本,与要求稍做了点改进
mysql> select
-> id,content,date,
-> case
-> from
-> when 5 then “自己”
-> else (select name from xb_user where id = from)
-> end as “发送者”,
-> case to
-> when 5 then “自己”
-> else (select name from xb_user where id = to)
-> end as “接收者”
-> from xb_chart
-> where (from = 5 or to = 5);
+—-+———————+————+—————+—————+
| id | content | date | 发送者 | 接收者 |
+—-+———————+————+—————+—————+
| 7 | 消息测试1 | 2017-06-11 | 自己 | NULL |
| 8 | test | 2017-07-10 | 自科专家2 | 自己 |
| 9 | test2 | 2017-07-10 | 自己 | 自科专家2 |
| 10 | test3 | 2017-07-10 | 自己 | 主编 |
+—-+———————+————+—————+—————+
4 rows in set (0.00 sec)

原创粉丝点击