在許多提示後,我試着將它結合以下兩個查詢。我認爲代碼是自我解釋的。結合兩個查詢與加入
表:
評論:ID(INT),用戶名(VARCHAR),autorpost(文本),評論(文本), id_post(INT),時間(TIME)
帖子(TEXT), date(DATE),longitude(FLOAT),latitude(FLOAT),title(TEXT), text(TEXT),town(TEXT),time() TIME)
$hostname='localhost';
$user='root';
$password='';
$useron = $_COOKIE['username'];
try {
$dbh = new PDO("mysql:host=$hostname;dbname=searchfood",$user,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "SELECT id_post
FROM comments
WHERE username = '$useron'
ORDER BY id DESC"; // oder (longitude between $loo and $lo or latitude between $laa and $la) versuchen
if ($own = $dbh->query($sql)) {// need to add this line in your code
// then after fetchColumn
$ownco = $own->fetchAll(PDO::FETCH_COLUMN, 0);
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
try {
$dbh = new PDO("mysql:host=$hostname;dbname=searchfood",$user,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "SELECT id, autorid, autor, date, longitude, latitude, title, text, town, time
FROM posts
WHERE id in (" . implode(",",$ownco) . ")
ORDER BY id DESC"; // oder (longitude between $loo and $lo or latitude between $laa and $la) versuchen
if ($resco = $dbh->query($sql)) {// need to add this line in your code
// then after fetchColumn
$resultcom = $resco->fetchAll();
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
我自己嘗試:
"SELECT posts.id, posts.autorid, posts.autor, posts.date, posts.longitude, posts.latitude, posts.title, posts.text, posts.town, posts.time, comments.id_post
FROM posts
INNER JOIN
comments
WHERE id = post_id
ORDER BY id DESC"
價值? –
你沒有忘記'ON table.column = table2.column2'嗎? [Mysql JOIN](https://dev.mysql.com/doc/refman/5.0/en/join.html) – Epodax