dongshi3605 2010-03-22 18:32
浏览 12

将第三个表添加到Join

This query works fine:

$sqlStr = "SELECT s.loginid, s.title, s.url, s.displayurl, l.username
             FROM submission AS s,
                  login AS l
            WHERE s.loginid = l.loginid
         ORDER BY s.datesubmitted DESC
            LIMIT 10";

Would this work if I wanted to join a third MySQL table (called "comment") to it?

$sqlStr = "SELECT s.loginid, s.submissionid s.title, s.url, s.displayurl, l.username, count(c.comment) countComments
             FROM submission AS s,
                  login AS l, 
                  comment AS c,
            WHERE s.loginid = l.loginid
              AND s.submissionid = c.submissionid
         ORDER BY s.datesubmitted DESC
            LIMIT 10";

Thanks in advance,

John

  • 写回答

3条回答 默认 最新

  • douliu3831 2010-03-22 18:35
    关注

    You should really be using joins, it's more clear and it keeps your join conditions out of your where clause. Also, when you want to add a 3rd table in, it's more consistent:

    Here's your original code, using explicit join syntax:

    SELECT      s.loginid, s.title, s.url, s.displayurl, l.username
    FROM        submission s
    INNER JOIN  login l ON l.loginid = s.loginid
    ORDER BY    s.datesubmitted DESC
    LIMIT       10
    

    Then, if you want to add a third table, it's easy:

    SELECT      s.loginid, s.title, s.url, s.displayurl, l.username
    FROM        submission s
    INNER JOIN  login l ON l.loginid = s.loginid
    INNER JOIN  comment c ON s.submissionid = c.submissionid
    ORDER BY    s.datesubmitted DESC
    LIMIT       10
    

    Also, here's a trick. If you the two columns you join on are the same name, you can use the USING syntax:

    INNER JOIN  login l USING (loginid)
    INNER JOIN  comment c USING(submissionid)
    
    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源