2011-10-23 36 views
0
CREATE TABLE IF NOT EXISTS `tweets_comment_tbl` (
    `tweet_comment_id` int(12) NOT NULL AUTO_INCREMENT, 
    `tweet_id` int(12) NOT NULL, 
    `tweets_comment` text NOT NULL, 
    `created` int(12) NOT NULL, 
    `changed` int(12) NOT NULL, 
    `uid` int(12) NOT NULL, 
    `userip` varchar(20) NOT NULL, 
    `referer` text NOT NULL, 
    `status` int(2) NOT NULL DEFAULT '1', 
    PRIMARY KEY (`tweet_comment_id`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; 

-- 
-- Dumping data for table `tweets_comment_tbl` 
-- 

INSERT INTO `tweets_comment_tbl` (`tweet_comment_id`, `tweet_id`, `tweets_comment`, `created`, `changed`, `uid`, `userip`, `referer`, `status`) VALUES 
(1, 1, 'COMMENT USER1', 1319395671, 1319395671, 3, '127.0.0.1', 'http://localhost/drupal_tutorial/', 1), 
(2, 2, 'comment admin user', 1319395724, 1319395724, 1, '127.0.0.1', 'http://localhost/drupal_tutorial/node', 1), 
(3, 2, 'USER COMMENTING HIS COMMENT', 1319395838, 1319395838, 3, '127.0.0.1', 'http://localhost/drupal_tutorial/', 1), 
(4, 2, 'ADMIN COMMENTING FOR HIS COMMENT', 1319395865, 1319395865, 1, '127.0.0.1', 'http://localhost/drupal_tutorial/node', 1), 
(5, 2, 'dddCOMMENT USER1: ADMIN DOING COMMENT FOR STATUS UPDATE1', 1319395905, 1319395905, 1, '127.0.0.1', 'http://localhost/drupal_tutorial/node', 1); 

我的第二個表右連接查詢返回空值的記錄

CREATE TABLE IF NOT EXISTS `tweets_tbl` (
    `tweet_id` int(11) NOT NULL AUTO_INCREMENT, 
    `tweets` text NOT NULL, 
    `created` int(12) NOT NULL, 
    `changed` int(12) NOT NULL, 
    `uid` int(12) NOT NULL, 
    `userip` varchar(20) NOT NULL, 
    `referer` text NOT NULL, 
    `status` int(2) NOT NULL DEFAULT '1', 
    PRIMARY KEY (`tweet_id`), 
    KEY `tweet_id` (`tweet_id`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; 

-- 
-- Dumping data for table `tweets_tbl` 
-- 

INSERT INTO `tweets_tbl` (`tweet_id`, `tweets`, `created`, `changed`, `uid`, `userip`, `referer`, `status`) VALUES 
(1, 'STATUS UPDATE 1', 1319395633, 1319395633, 1, '127.0.0.1', 'http://localhost/drupal_tutorial/node', 1), 
(2, 'Status update user1', 1319395696, 1319395696, 3, '127.0.0.1', 'http://localhost/drupal_tutorial/node', 1); 

試圖連接查詢

SELECT ut.picture as picture, tct.tweet_id as tweet_id, tct.tweets_comment as tweets_comment, tct.changed 
FROM tweets_comment_tbl tct 
RIGHT JOIN users as ut ON tct.uid=ut.uid AND tct.tweet_id=2 AND tct.status = 1 
order by tct.created desc 

回報記錄,上面的查詢

picture   tweet_id tweets_comment changed 
        1   COMMENT USER1 1319395671 
       NULL NULL  NULL 
picture-1.png NULL NULL  NULL 

其實我的預期是

爲什麼查詢已經返回NULL記錄,我不知道我在連接查詢中犯了錯誤。

+0

'right outer join'通過設計生成空值。如果你不想要空值(我建議你不要),那麼就避免外連接。 – onedaywhen

+0

如何在沒有連接的情況下完全填充以上輸出 –

回答

2

查詢返回用戶的所有行,並基於ON中的條件加入tweets_comment_tbl。如果tweets_comment_tbl中沒有記錄與用戶ID匹配,則users的記錄仍然包含在記錄集中。如果您只想看到帶評論的用戶,則可能需要INNER JOIN

附註:
我認爲幾乎總是可以避免RIGHT JOIN;與LEFT JOIN查詢是更容易閱讀和理解。

+0

我同意'LEFT JOIN'比右邊更容易閱讀,即使它們返回相同的結果。 –

+0

我不同意LEFT JOIN更容易閱讀。 – onedaywhen