如何只使用union all回显一个参数

时间:2016-11-10 07:08:45

标签: php mysql

我必须要数据库表。我想从两个表中打印联合所有名称,如果出现多个名称,则只打印一次并将其设置为红色。 我的PHP:

<?php
    include 'verification/verify_form_details.php';

    $result5 = getUsers();
    if (!$result5) {
        die('Invalid query: ' . mysqli_error());
    }   
    while($row5 = mysqli_fetch_array($result5))
    {  
        $username = $row5['username'] ;
        echo '<ul>';    
        echo"<li>". $username ."</li>";
        echo '</ul>';   
    }           
?>

我的疑问:

function getUsers()
{
    global $con;
    $sql = "SELECT username FROM `user_project` 
            UNION ALL 
            SELECT username FROM `user`";
    return mysqli_query($con,$sql); 
}

我如何实现这一目标?

2 个答案:

答案 0 :(得分:1)

将您的查询修改为按用户名分组

    $sql = "SELECT username FROM 
            (
            SELECT username FROM `user_project` 
            UNION ALL 
            SELECT username FROM `user`
            )
            GROUP BY username";

此外,如果你想获得多少外观,那么你可以使那些有多次出现的红色

$sql = "SELECT username, count(username) FROM 
                (
                SELECT username FROM `user_project` 
                UNION ALL 
                SELECT username FROM `user`
                )
                GROUP BY username";

答案 1 :(得分:0)

$sql = "SELECT username FROM 
        (
        SELECT username FROM `user_project` 
        UNION ALL 
        SELECT username FROM `user`
        )
        GROUP BY username";

添加&#39; distinct&#39;到这个