1
在我的數據庫中,我有一個名爲posts
的表和一個名爲topics
的表。SQL JOIN爲每一行返回帶有錯誤ID的查詢
每個post
有一個家長topic
。
在這種情況下posts.parent_topic
是一個外鍵關聯topics.id
我attemping做一個JOIN
讓我的查詢將從topics
表返回正確的topics.topic_title
。我已經能夠成功地做到這一點,但我注意到,我不再爲返回的任何東西獲得正確的posts.id
。
我的查詢:
$posts = $db->query("
SELECT
*
FROM
posts
JOIN topics ON
posts.post_parent_topic = topics.id
ORDER BY
posts.created_on DESC
")->fetchALL(PDO::FETCH_ASSOC);
在$posts
可變我看到這些結果做了var_dump
後:
array (size=2)
0 =>
array (size=12)
'id' => string '1' (length=1) // this id is CORRECT for the post
'post_parent_topic' => string '1' (length=1)
'created_on' => string '2015-11-03 09:30:40' (length=19)
'post_title' => string 'Development Standards' (length=21)
'post_content' => string 'These are the development specifc standards.' (length=44)
'topic_title' => string 'Code Standards' (length=14)
'topic_content' => string 'These are the company programming standards.' (length=44)
'topic_parent_organization' => string '1' (length=1)
1 =>
array (size=12)
'id' => string '1' (length=1) // this id is INCORRECT for the post, it should be an id of 2 (as it appears in the database)
'post_parent_topic' => string '1' (length=1)
'created_on' => string '2015-11-03 09:30:40' (length=19)
'post_title' => string 'Design Standards' (length=16)
'post_content' => string 'These are the design specific standards.' (length=40)
'topic_title' => string 'Code Standards' (length=14)
'topic_content' => string 'These are the company programming standards.' (length=44)
'topic_parent_organization' => string '1' (length=1)
爲什麼每個帖子返回相同的id
?我需要這篇文章的id
,因爲它在我的數據庫中。
有'ID ''帖子'表中的列? –
你確定'id'來自'topics'而不是'posts'。通常最好先使用'AS'對每個表和字段進行別名,這樣您就可以看到哪個字段屬於每個表。 (即'SELECT p.id AS'posts_id',t.id AS'topics_id'FROM posts AS p LEFT JOIN topics AS t ON p.post_parent_topic = t.id ORDER BY p.created_on DESC') –
@YeldarKurmangaliyev yes there是每個表中的id列。 – captainrad