【发布时间】:2018-04-06 18:46:30
【问题描述】:
我有一个查询,它通过 JOIN 从不同的表中选择值。但我想我现在有一个问题,因为一个表需要以不同的名称再次加入,但不知何故它不起作用。
基于社交网络结构的示例:
表“用户”:
+--------+-----------+
| userid | username |
+--------------------|
| 1 | userOne |
| 2 | userTwo |
| 3 | userThree |
+--------+-----------+
表“帖子”:
+--------+---------+-------------------------------+
| postid | userid | text |
+--------------------------------------------------|
| 102 | 1 | "Haha i'm User one" |
| 103 | 1 | "And User one is the best" |
| 104 | 3 | "I'm having fun with user two"|
+--------+---------+-------------------------------+
表“用户标签”:
+--------+---------------+
| postid | tagged_userid |
+------------------------|
| 104 | 2 |
+--------+---------------+
这是我的查询:
SELECT posts.postid,
posts.userid,
posts.text,
users.username,
IFNULL(GROUP_CONCAT(DISTINCT usertags.tagged_userid SEPARATOR ','), NULL) as
taggedusers_id,
IFNULL(GROUP_CONCAT(DISTINCT taggedusers.fullname SEPARATOR ','), NULL) as
taggedusers_name,
FROM posts
JOIN users ON posts.userid = users.userid
LEFT JOIN usertags ON posts.postid = usertags.postid
LEFT JOIN users as taggedusers ON usertags.tagged_userid = users.userid
GROUP BY posts.postid
ORDER BY posts.postid DESC
这就是我得到的结果:
+--------+---------+---------------------------------------------------------------------+
| postid | userid | text | username | taggedusers_id |
+-----------------------------------------------------------------------|----------------|
| 102 | 1 | "Haha i'm User one" | userOne | NULL |
| 103 | 1 | "And User one is the best" | userOne | NULL |
| 104 | 3 | "I'm having fun with user two"| userThree | 2
+--------+---------+-------------------------------+--------------------+----------------+
问题: 'taggedusers_name' 列显示,但它始终显示为 NULL。我希望它显示被标记的用户的用户名。 像这样,但总的来说,输出很大
+---------------+-------------------+
| taggeduser_id | taggeduser_name |
+-----------------------------------|
| 2 | userTwo |
| 2,3 | userTwo,userThree |
| NULL | NULL |
+---------------+-------------------+
那么,这怎么可能呢?我需要制作多个 SELECT 语句吗?我已经试过了,但我也失败了:/ 我很乐意提供帮助!
【问题讨论】:
-
您的示例数据与您想要的输出不匹配,架构也不完整,您缺少查询中使用的列。
-
无关,
IFNULL(***, NULL)的意义何在?基本上,您是说,如果是NULL,请将其设置为NULL。似乎是多余的,除非我错过了一个好处。 -
@KeithChason 可能是指
IFNULL(***, '')
标签: mysql list join concat group-concat