为用户选择正确的数据

时间:2013-03-26 07:01:18

标签: php mysql select

我的数据库中有两个表

enter image description here

表任务的U_ID是表用户的id的外键

我的代码就像这样

<?php
    require("common.php");
    if(empty($_SESSION['user']))
    {
        header("Location: login.php");
        die("Redirecting to login.php");
    }
    $query = "
        SELECT
            id,
            username,
            eID
        FROM users
        WHERE id <> '5'
    ";
    $query1 = "
        SELECT
            T_ID,
            task_tom,
            U_ID
        FROM tasks
        ORDER BY T_ID DESC LIMIT 1

    ";
    try
    {
        $stmt = $db->prepare($query);
        $stmt->execute();
    }
    catch(PDOException $ex)
    {
        die("Failed to run query: " . $ex->getMessage());
    }
    $rows = $stmt->fetchAll();

        try
    {
        $stmt1 = $db->prepare($query1);
        $stmt1->execute();
    }
    catch(PDOException $ex)
    {
        die("Failed to run query: " . $ex->getMessage());
    }
    $rows1 = $stmt1->fetchAll();
?>
<h1>Memberlist</h1>
<table border="1">
    <tr>
        <th>Username</th>
        <th>Employee ID</th>
        <th>Task</th>
    </tr>
    <?php foreach($rows as $row): foreach($rows1 as $row1): ?>
        <tr>
            <td><?php echo htmlentities($row['username'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo htmlentities($row['eID'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo $row1['task_tom']; ?></td>
           <?php endforeach; endforeach;?>
</table>
<br/>
<a href="edit_account.php">Edit Account</a><br /><a href="logout.php">Logout</a>  

我的问题是我如何填充表格中的任务栏,对应右边的U_ID 这段代码将为我提供这个答案

enter image description here

据推测,SSIS(数据挖掘)只是分配给bassil的task_tom而劳伦斯应该有一个空白的任务,因为用户还没有为劳伦斯输入任何任务,但似乎我的选择陈述存在缺陷或是我的对于每一个,它在桌面上打印给每个用户。所以我的问题是如何解决这类问题?

3 个答案:

答案 0 :(得分:1)

SELECT
    U.id,
    U.username,
    U.eID, 
    t.task_tom

FROM 
    users u

  INNER JOIN 
   (
      SELECT u_id, max(t_id) as t_id
      FROM tasks
      GROUP BY u_id
   ) tmax
  ON tmax.U_ID = u.id

  INNER JOIN tasks t ON t.t_id = tmax.t_id

WHERE u.id <> '5'

这基本上说“每个用户的最新任务ID是什么,现在可以获取有关该任务的所有信息”。

答案 1 :(得分:0)

JOIN您的表格使用LEFT JOINRIGHT JOININNER JOIN根据您的要求。

    SELECT
        id,
        username,
        eID,
        T_ID,
        task_tom,
        U_ID
    FROM users
    LEFT JOIN tasks ON tasks.U_ID = users.id
    WHERE users.id <> '5'
    ORDER BY tasks.T_ID DESC
    GROUP BY users.id

编辑答案,但我不确定

的工作原理
ORDER BY tasks.T_ID DESC
GROUP BY users.id

答案 2 :(得分:0)

$query="SELECT U.id,T.T_ID,task_tom FROM users U LEFT JOIN tasks T ON U.id = T.T_ID WHERE id <> '5' ORDER BY T.T_ID DESC group by U.id";