2012-10-29 100 views
1

我有2個表如下:Mysql的innerjoin條款不工作

talk

topic_id | topic_name | user_id (user who create topic) 
    1   test1  1 
    2   test2  2 

talk_reply

talk_reply_id | message | topic_id | user_id (user who reply to specific topic) 
    1   hi1  1   3 
    2   hi2  1   4 

user

user_id | name 
    1  mark 
    2  pedro 
    3  gates 
    4  steve 

我的查詢如下:

SELECT `tr`.`message`, 
     `tr`.`user_id`, 
     `tr`.`topic_id`, 
     `u`.`name` 
FROM `talk_reply` AS `tr` 
INNER JOIN `users` AS `u` ON tr.user_id = u.user_id WHERE (tr.topic_id=1) 

但我只得到1分的結果,而不是2,我缺少什麼嗎?謝謝。

+0

你想得到什麼? –

+0

我想從talk_reply表中獲取回覆特定主題的用戶的名稱,在這種情況下topic_id 1 – d3bug3r

+0

@zlippr - 您提供的數據返回兩行。實際上*使用的數據中有一個錯誤,您沒有向我們展示* actual *語句,或者MySQL的sql引擎包含嚴重錯誤。我懷疑這是後者:) –

回答

0

使用此:

SELECT `tr`.`message`, 
     `tr`.`user_id`, 
     `tr`.`topic_id`, 
     `u`.`name` 
FROM `talk_reply` AS `tr` 
AND `users` AS `u` 
WHERE tr.user_id = u.user_id AND (tr.topic_id=1) 
+0

如果where子句不起作用,那麼... –

+0

無法正常工作#1064 - 您的SQL語法有錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在'AND'用戶附近使用正確的語法AS'u' WHERE tr.user_id = u.user_id AND tr.topic_id = 1第6行限制0,30' – d3bug3r

1
SELECT t.topic_id, t.user_id, u.name, tr.message 
FROM talk t 
INNER JOIN talk_reply tr ON tr.topic_id = t.topic_id 
INNER JOIN users u ON u.user_id = t.user_id 
WHERE t.topic_id = '1' 

UPDATE

SELECT tr.topic_id, tr.user_id, u.name, tr.message 
FROM talk_reply tr 
INNER JOIN users u ON u.user_id = tr.user_id 
WHERE tr.topic_id = '1' 
+0

謝謝有用!! – d3bug3r

+0

@zlippr:很高興幫助你:) –

+3

OP的選擇列表是不同的,他只需要來自talk_reply和用戶表的列。他的查詢很好,它應該工作。無需在這裏使用談話表 – AnandPhadke

1
SELECT tr.`message`, 
     tr.`user_id`, 
     tr.`topic_id`, 
     (select u.`name` from users u where u.user_id = tr.user_id) name 
FROM `talk_reply` as tr 
WHERE tr.topic_id=1 

SQLFIDDLE DEMO

+0

只返回1結果 – d3bug3r

+0

試試這個更新的查詢 – AnandPhadke

+0

好吧得到它,謝謝.. – d3bug3r

1
select a.topic_id, a.user_id,b.message,c.name 
from talk a 
inner join talk_reply.b on a.topic_id=b.topic.id 
inner join users c on c.user_id=a.user_id 
where t.topic_id=1;