使用两个表。我在这做错了什么?

时间:2013-05-04 00:13:19

标签: sql join union

我想创建一个活动供稿系统,我的供稿(状态)和朋友在我的数据库中的不同表中。如何连接它们以便登录用户只能从他们的朋友那里接收提要。

<?php
$sql = "
SELECT * FROM status WHERE author='(friend of logged-in user)' AND type='a'
**UNION** 
SELECT * FROM friends WHERE user1='$user' AND accepted='1' OR user2='$user' AND accepted='1' 
";
$query = mysqli_query($database, $sql);
$statusnumrows = mysqli_num_rows($query);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
    $user1 = $row["user1"];
    $user2 = $row["user2"];
    $accepted = $row["accepted"];
    $statusid = $row["id"];
    $account_name = $row["account_name"];
    $author = $row["author"];
    $postdate = $row["postdate"];
    $postdate = strftime("%b %d, %Y %I:%M %p");
    $data = $row["data"];
    $data = nl2br($data);
    $data = str_replace("&amp;","&",$data);
    $data = stripslashes($data);
    $statusDeleteButton = '';
    if($author == $log_username || $account_name == $log_username ){
        $statusDeleteButton = '<span id="sdb_'.$statusid.'"><a href="#" onclick="return false;" onmousedown="deleteStatus(\''.$statusid.'\',\'status_'.$statusid.'\');" title="DELETE THIS STATUS AND ITS REPLIES">delete status</a></span> &nbsp; &nbsp;';
    }

    $feedlist .= '<div id="status_'.$statusid.'" class="flipwrapper pin">
        <div class="picture">
        <header class="img-btm">
            '.$postdate.'</b><br />
            20 <a href="#">cmts</a>&nbsp;255 <a href="#">likes</a>&nbsp; '.$statusDeleteButton.'
        </header>
        <a href="status_frame.php?id='.$statusid.'"><img id="bound" src="'.$data.'"/></a></div></div>';
}
?>

1 个答案:

答案 0 :(得分:1)

你绝对不希望在这里使用UNION,而是一个或多或少像这样的子查询:

SELECT * FROM status 
WHERE author in (
        SELECT whateverfieldshouldmapfromfriendstoauthor FROM friends 
        WHERE user1='$user' AND accepted='1' OR user2='$user' AND  accepted='1' 
    ) AND type='a'

以及一些一般提示:

  • 直接使用脚本语言(在本例中为php)开发查询是一个非常糟糕的主意。使用允许您开发查询,运行查询和检查结果集的工具。有很多这样的,比如MySQL自己的WorkbenchSquirrel SQL
  • 要非常小心SQL注入问题(如果请求提供了$user变量,那么)。避免SQL注入问题的最佳方法是使用parameterized queries