如何从2表中获得结果并且不显示重复项

时间:2012-11-13 19:29:47

标签: php mysql

我有2张桌子

USERS
------------
id   | user
1    | john
2    | George
3    | Andy

Text
--------------------------------
id | user |date        |text
1  |  1   |2012/10/2   | ABC
2  |  3   |2012/11/2   | ABCD
3  |  2   |2012/12/2   | ABCDE
4  |  2   |2012/1/2    | ABCDE

Text表格中,user列从id表中获取Users

我有以下查询:

   $sql= mysql_query ("SELECT
    user.id,
    users.user,
    CASE
        WHEN text.date = CURDATE() THEN '1'
        ELSE '0'
    END AS 'today',
    text.date,
    text.text
FROM  users user, text text
WHERE users.id = text.user;");

if (mysql_num_rows($sql)<=0)
echo  "NO ENTRIES FOUND";

while ($row = mysql_fetch_assoc($sql))
{

          $user =$row['user'];  
           $id  =$row['id'];  
             $date2  =$row['date'];  

            if ($row['today'] == 1) { echo"
 <div class='z'><a href='viewuser.php?id=$user'>$user</a></div><br>         
        "; } else { echo"
 <div class='zx'><a href='viewuser.php?id=$user'>$user</a></div><br>         
        "; }; 

}

我的问题是:

如何显示日期与当前日期相同的用户,第一个div(zx),如果不是第二个div(z),则从2个表中进行比较并显示一次,如果是2倍用户。

1 个答案:

答案 0 :(得分:1)

<!-- language: lang-sql -->

SELECT
    u.id,
    u.user,
    CASE
        WHEN t.date = CURDATE() THEN '1'
        ELSE '0'
    END AS 'today',
    t.date,
    t.text
FROM  users u, text t
WHERE u.id = t.user;

现在显示结果只是说

if ($row['today'] == 0) { class="zx"; } else { class="z"; }

代码是缩写的,如果您需要详细说明,请告诉我。

以下是我的解决方案的更新代码:

$sql = mysql_query ("
SELECT
    u.id,
    u.user,
    CASE
        WHEN MAX(t.date) = CURDATE() THEN '1'
        ELSE '0'
    END AS 'today'
FROM  users u, text t
WHERE u.id = t.user
GROUP BY u.id, u.user");

if (mysql_num_rows($sql) <= 0)
    echo  "NO ENTRIES FOUND";

while ($row = mysql_fetch_assoc($sql))
{
    $user =$row['user'];
    $id =$row['id']; 


if ($row['today'] == 1) {
     echo "<div class='zx'><a href='viewuser.php?id=$id'>$user</a></div><br>";
} else {
     echo "<div class='z'><a href='viewuser.php?id=$id'>$user</a></div><br>";
}

}