3表加入其中的添加

时间:2011-03-17 20:17:39

标签: php mysql sql

    $sql_select = "SELECT p.ideaTitle, f.feedback, f.contact
    FROM ideas p
    RIGHT JOIN feedback f ON f.ideaSlug = p.ideaSlug
    ORDER BY p.ideaDateTime, f.dateTime
     ";

这就是我在新桌子上工作的内容。我希望它显示ideaTitle,每个ideaTitle的所有反馈(上面都有),然后我们在下面的sql代码中得到的投票总数(布尔值1和0)。我只是花时间以正确的方式组合它们。将它分解为2个单独的sql命令会更好吗?

    SELECT "p.ideaTitle,
          SUM(CASE WHEN v.vote = '1' THEN 1 ELSE 0 END) AS yesCount,
          SUM(CASE WHEN v.vote = '0' THEN 1 ELSE 0 END) AS noCount
         FROM ideas p
    LEFT JOIN votes v ON v.ideaSlug = p.ideaSlug
     GROUP BY p.ideaSummary
     ORDER BY yesCount DESC
     LIMIT 20";

当前代码我用来显示数据。

                $result = mysql_query($sql_select,$link) or die("Insertion Failed:" . mysql_error());   
                $x=0;
                while ($row = mysql_fetch_array($result)) {
                    if ($row['ideaTitle'] != $previousTitle) {
                        ?> <h3> <?php echo stripslashes($row['ideaTitle']); ?> </h3>
                       <h4> Yes: <?php // echo $number of yes votes; ?> </h4>
                       <h4> No:  <?php // echo $number of no votes; ?></h4>
                    <?php } ?>
                    <blockquote>
                    <p><em> <?php echo stripslashes($row['feedback']); ?> </em> </p></blockquote>
                    <?php 
                    $previousTitle = $row['ideaTitle']; ?>
                <?php }

1 个答案:

答案 0 :(得分:1)

我这是两个单独的查询。您可以在一个查询中执行此操作,但这样做没有任何实际意义。

如果确实想要尝试在一个查询中执行此操作,它可能看起来像这样:

SELECT p.ideaTitle, f.feedback, f.contact, p2.yesCount, p2.noCount
FROM ideas p
LEFT JOIN feedback f ON f.ideaSlug = p.ideaSlug
LEFT JOIN (
    SELECT
        p.ideaSlug,
        SUM(CASE WHEN v.vote = '1' THEN 1 ELSE 0 END) AS yesCount,
        SUM(CASE WHEN v.vote = '0' THEN 1 ELSE 0 END) AS noCount
    FROM ideas p
    LEFT JOIN votes v ON v.ideaSlug = p.ideaSlug
    GROUP BY p.ideaSlug
) p2
ON p.ideaSlug = p2.ideaSlug

但是我没有看到这样做有任何好处,我看到了一些缺点。