合并重复值

时间:2018-04-04 11:13:17

标签: php mysql join group-by grouping

我有三个表:projectsproj_categcategories

projects(id, title)
proj_categ(id, proj_id, categ_id)
categories(id, title)

proj_categ连接两个表(projectscategories),如下所示。 一个项目可能有一个或多个类别。 enter image description here

PHP& MySQL的

$projects = mysql_query("SELECT * FROM projects"); 

while($projrow=mysql_fetch_array($projects))
{
    $projid = $projrow['id'];

    $categories= mysql_query("SELECT * FROM categories JOIN proj_categ ON categories.id=proj_categ.categ_id where proj_id='".$projid."'"); 

    while($caterow=mysql_fetch_array($categories))
    {
        echo $caterow['title']." ";
        echo $projrow['title']."<br/>";
    }
}

仅供参考:HTML代码

$caterow['title']要插入<li class="gallery-item Singapore Indonesia"> $projrow['title']要插入<span class="title">Title</span>

<li class="gallery-item Singapore Indonesia">
    <div class="gallery-contents">
        <div id="id1" class="thumbnail gallery-trigger">
            <span>
                <span class="title">Title</span>
                <img src="images/project.jpg" alt="" />
            </span>
        </div>
    </div>
</li>

结果

    projects.title |categories.title
   +---------------+-----------------
    "Testing 1"    |   "Singapore"
    "Testing 2"    |   "Malaysia"
    "Testing 3"    |   "Indonesia"
    "Testing 4"    |   "Singapore"
    "Testing 4"    |   "Malaysia"
    "Testing 5"    |   "Singapore"
    "Testing 5"    |   "Malaysia"
    "Testing 5"    |   "Indonesia"
    "Testing 6"    |   "Indonesia"
    "Testing 7"    |   "Malaysia"
    "Testing 7"    |   "Indonesia"

我想要什么

我不想重复的项目,我希望结合相同的项目,但具有不同的类别。试过GROUP BY,但它对我不起作用。希望你们中的一些人可以给我一些建议。谢谢!

3 个答案:

答案 0 :(得分:1)

SELECT GROUP_CONCAT(categories.title) as "categories.title",
       proj_categ.title as "projects.title"
FROM categories
JOIN proj_categ ON categories.id=proj_categ.categ_id
WHERE proj_id=$projid
GROUP BY proj_categ.title;

答案 1 :(得分:1)

为什么你不使用一个查询

$projects = mysql_query("SELECT projects.title as proj_title,categories.title as cat_title  FROM projects JOIN proj_categ ON projects.id=proj_categ.proj_id JOIN categories ON categories.id=proj_categ.categ_id"); 

while($projrow=mysql_fetch_array($projects))
{
    echo $projrow['proj_title']." ";
    echo $projrow['cat_title ']."<br/>";
}

同样 mysql _ * 已弃用并从PHP 7 mysqli_ *或PDO 中删除。

答案 2 :(得分:0)

$res = array();

$projects = mysql_query("SELECT * FROM projects"); 

while($projrow=mysql_fetch_array($projects))
{
    $projid = $projrow['id'];

    $res[$projid] = array('title' => $projrow['title'], 'categories' => array());

    $categories= mysql_query("SELECT * FROM categories JOIN proj_categ ON categories.id=proj_categ.categ_id where proj_id='".$projid."'"); 

    while($caterow=mysql_fetch_array($categories))
    {
        echo $caterow['title']." ";
        echo $projrow['title']."<br/>";

        $res[$projid]['categories'][] = $caterow['title'];
    }
}