来自两个不同表的mySQL查询,具有相互条件

时间:2011-08-30 21:45:24

标签: mysql multiple-tables

请帮我构建mysql查询

我有2张桌子,#_ udjacomment和# _content

目前我有查询:

$query  = "SELECT udja.id";

      if( $include_author == 1 ) $query .= ", udja.full_name";
      if( $include_date == 1 ) $query .= ", udja.time_added";
      if( $include_comment == 1 ) $query .= ", if(CHAR_LENGTH(udja.content) > ".$content_number_of_characters.", SUBSTR(udja.content, 1, ".$content_number_of_characters."), udja.content) AS content";
      if( $include_link_to_comment == 1 ){ 
        $query .= ", CASE WHEN LOCATE('com_content:', udja.comment_url) > 0 
        THEN CONCAT(SUBSTRING_INDEX(udja.comment_url,':',-1),'-', com_content.alias, '.html')
        ELSE udja.comment_url END AS comment_url";
        }

      $query .= " FROM #__udjacomments AS udja, #__content AS com_content WHERE udja.is_published = 1 AND com_content.id = SUBSTRING_INDEX(udja.comment_url,':',-1) AND com_content.checked_out = 0 ORDER by udja.id DESC limit ".$number_of_comments;

但我没有得到正确的结果。如果我停止尝试从表#__content AS com_content访问,那么我得到#__udjacomment AS udja正确的结果

所以,我想我问的是如何指出并包含我想要字段的约束com_content.alias WHERE com_content.id = SUBSTRING_INDEX(udja.comment_url,':',-1)

在某些情况下,udja.comment_url的格式为com_content:22,com_content:19

在其他情况下,udja.comment_url会有一个像word-word-another-word这样的字符串

这就是为什么我在条件if($ include_link_to_comment == 1)中有更广泛的声明

更新:最终查询这一点(我实施了响应者建议和更改案例声明以及声明的声明)

 $query  = "SELECT udja.id";

      if( $include_author == 1 ) $query .= ", udja.full_name";
      if( $include_date == 1 ) $query .= ", udja.time_added";
      if( $include_comment == 1 ) $query .= ", if(CHAR_LENGTH(udja.content) > ".$content_number_of_characters.", SUBSTR(udja.content, 1, ".$content_number_of_characters."), udja.content) AS content";
      if( $include_link_to_comment == 1 ){ 
        $query .= ", CASE 
            WHEN LOCATE('com_content:', udja.comment_url)<>0
            THEN CONCAT(SUBSTRING_INDEX(udja.comment_url,':',-1),'-', com_content.alias, '.html')
            ELSE udja.comment_url 
            END AS comment_url";

        }
//          THEN CONCAT(SUBSTRING_INDEX(udja.comment_url,':',-1),'-', com_content.alias, '.html')
      $query .= " FROM #__udjacomments AS udja
                    LEFT JOIN #__content AS com_content 
                        ON com_content.id = SUBSTRING_INDEX(udja.comment_url,':',-1) 
                    WHERE udja.is_published = 1 ORDER by udja.id DESC limit ".$number_of_comments;

1 个答案:

答案 0 :(得分:0)

您需要使用外部联接:

...
FROM #__udjacomments AS udja
LEFT JOIN #__content AS com_content 
    on com_content.id = SUBSTRING_INDEX(udja.comment_url,':',-1)
WHERE ...