两个表,显示与ID匹配的一个结果

时间:2017-01-24 09:42:26

标签: php mysql

我有两张桌子:

post_languages ,其中包含以下列: languageID languageName

post_to_languages postID postLanguage

我想要实现的是显示与帖子相关的所有语言。

示例:帖子1,语言:法语,俄语

也许我的做法是错的,但这是我尝试过的方法之一:

//get language id
$stmt2 = $db->prepare('SELECT languageID FROM post_to_languages WHERE postID = :postID');
$stmt2->execute(array(':postID' => $row['postID']));

//Count total number of rows
$rowCount2 = $stmt2->rowCount();

if ($rowCount2 > 0) {
    $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
    foreach ($row2 as $langID) {
        $stmt3 = $db->prepare('SELECT languageName FROM post_languages WHERE languageID = :languageID');
        $stmt3->execute(array(':languageID' => $langID));
        $row3 = $stmt3->fetch();
        $lang_string = $row3['languageName'];
    }
} else {
    $lang_string = "Unknown";
} 

不管我尝试的是什么,我只能使用一种语言。也许我应该首先按ID选择post_to_languages。

2 个答案:

答案 0 :(得分:1)

您不需要此嵌套循环,尝试连接或子查询。显示子查询。如果您有大量行,则内部联接会更快。但是子查询仍然比嵌套循环更快。

SELECT languageName FROM post_languages WHERE languageID IN 
 (SELECT languageID FROM post_to_languages WHERE postID = :postID')

如果您仍然没有看到任何结果,请将:postID替换为实际值并在控制台中尝试。

答案 1 :(得分:0)

从diff中选择不同的列。表。 在表post_to_language中,必须与languageId具有相同的数据类型。

请尝试此代码

//获取语言ID

$stmt2 = $db->prepare('SELECT postLanguage FROM post_to_languages WHERE postID = :postID');
$stmt2->execute(array(':postID'=>$row['postID']));

    //Count total number of rows
    $rowCount2 = $stmt2->rowCount();

    if($rowCount2 > 0){

     $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);

   foreach($row2 as $langID) {

      $stmt3 = $db->prepare('SELECT languageName FROM post_languages WHERE languageID = :languageID');
     $stmt3->execute(array(':languageID'=>$langID));

    $row3 = $stmt3->fetch();
    $lang_string = $row3['languageName'];

    }

    } else {
          $lang_string = "Unknown";
    }  

谢谢。