如何使用MYSQL GROUP_CONCAT获取两个变量?

时间:2016-08-26 15:58:40

标签: php mysql

我有一个显示照片($file)的网页,每张照片下面都是“喜欢”每张照片的用户列表。 每个用户都显示为其个人资料的html链接。目前,用户通过其user_names显示和链接:

<a href=\"profile.php?user_name=".$tag.">".$tag."</a>

但我想知道如何显示用户名,但使用$user_id链接到他们的个人资料。像

这样的东西
<a href=\"profile.php?user_name=".$user_id.">".$tag."</a>

我在查询中使用GROUP_CONCAT来获取喜欢来自($tag)的每张照片的所有user_id的tbl_collab,然后在tbl_users上加入这些结果以获取user_name但是我无法弄清楚如何在html链接中显示user_id和user_name。谁能告诉我这是怎么做到的?

//Database Query
$sql="SELECT up.file,p.user_name,p.user_id, GROUP_CONCAT(cp.user_name)
FROM tbl_uploads up
LEFT JOIN tbl_users p ON up.user_id = p.user_id
LEFT JOIN tbl_collab c ON up.file = c.file
LEFT JOIN tbl_users cp ON cp.user_id = c.collab_userid
GROUP BY up.file";

$result = $mysqli->query($sql);
while($row = $result->fetch_array())
{
    $user_id = explode (",", $row['user_id'] );
    $user = explode (",", $row['user_name'] );
    $files = explode (",", $row['file']);
    $tag_array = explode(',' , $row['GROUP_CONCAT(cp.user_name)']);

    foreach($files as $file) {

    //File is displayed here

    }
    foreach($tag_array as $tag) {

        //Links to the users who liked the file

        <a href=\"profile.php?user_name=".$tag.">".$tag."</a>

    }
}

2 个答案:

答案 0 :(得分:2)

在SQL中

获取GROUP_CONCAT中的两个值:

GROUP_CONCAT(CONCAT(cp.user_id,'~',cp.user_name) SEPARATOR '|') AS tagGroup

在你的foreach中为标签数组:

$tag_array = explode('|' , $row['tagGroup']);

foreach($tag_array as $tag) {
    list($uid,$uname) = explode('~',$tag,2);

    echo "<a href=\"profile.php?user_id=".$uid.">".$uname."</a>";
}

(更新后使用@ Jakumi的评论和更多示例以清晰显示 - 请注意我使用&#39; |&#39;作为GROUP_CONCAT分隔符,作为字符转义问题对于&#34; \ n&#34;这里很麻烦)

祝你好运!

答案 1 :(得分:2)

您不需要使用GROUP_CONCAT,只需执行普通JOIN并使用ORDER BY将同一文件的所有行放在一起。

<?php
//Database Query
$sql="SELECT up.file,p.user_name,p.user_id, cp.user_name as liker_name, cp.user_idas liker_id
FROM tbl_uploads up
LEFT JOIN tbl_users p ON up.user_id = p.user_id
LEFT JOIN tbl_collab c ON up.file = c.file
LEFT JOIN tbl_users cp ON cp.user_id = c.collab_userid
ORDER BY up.file";


$result = $mysqli->query($sql);
$last_file = null
while($row = $result->fetch_array())
    {
        $user_id = $row['user_id'];
        $user = $row['user_name'];
        $files = $row['file'];
        $liker_id = $row['liker_id'];
        $liker_name = $row['liker_name'];
        if ($file != $last_file) {
            $last_file = $file;
            //File is displayed here
        }
        //Links to the users who liked the file
        echo "<a href=\"profile.php?user_name=".$liker_id.">".$liker_name."</a>
    }