0

i have two tables ...first is entry

CREATE TABLE IF NOT EXISTS `entry` (
  `entry_id` int(11) NOT NULL AUTO_INCREMENT,
  `entry_cat_id` int(11) NOT NULL,
  `entry_name` varchar(255) NOT NULL,
  `entry_body` text NOT NULL,
  `img_url` varchar(255) NOT NULL,
  `image_link` varchar(255) NOT NULL,
  `entry_state` tinyint(1) DEFAULT '0',
  `comment_count` int(11) NOT NULL DEFAULT '0',
  `entry_count` int(11) NOT NULL DEFAULT '0',
  `entry_created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`entry_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=41 ;

--
-- Dumping data for table `entry`
--

INSERT INTO `entry` (`entry_id`, `entry_cat_id`, `entry_name`, `entry_body`, `img_url`, `image_link`, `entry_state`, `comment_count`, `entry_count`, `entry_created`) VALUES
(27, 15, 'title fot entry', 'content', '', '', 0, 0, 0, '2013-04-14 14:47:56');

and the escond is entry_category

CREATE TABLE IF NOT EXISTS `entry_category` (
  `category_id` int(11) NOT NULL AUTO_INCREMENT,
  `category_name` varchar(150) NOT NULL,
  `slug` varchar(150) NOT NULL,
  `cat_created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`category_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=16 ;

--
-- Dumping data for table `entry_category`
--

INSERT INTO `entry_category` (`category_id`, `category_name`, `slug`, `cat_created`) VALUES
(10, 'rrrrrrrr', 'rrrrrrr', '0000-00-00 00:00:00'),
(15, 'gggggg', 'ttttttttt', '2012-12-10 13:47:28');

when select with inner join to get the category and entry name i see category_name is null

SELECT entry.entry_id, entry_category.category_name, entry.entry_name
FROM entry
INNER JOIN entry_category
ON entry.entry_id=entry_category.category_id;

why and what i shall do to see the the category name

4

2 回答 2

1

我认为你加入了错误的领域。当我认为您想加入 entry.entry_cat_id 字段时,您将加入 entry.entry_id 字段。

尝试将您的查询更改为:

SELECT entry.entry_id, entry_category.category_name, entry.entry_name
FROM entry
    INNER JOIN entry_category
        ON entry.entry_cat_id=entry_category.category_id;

顺便说一句——您现有的查询不应该从您的示例数据中返回任何结果。要查看NULLentry_category 表中的记录,您需要使用OUTER JOIN.

于 2013-05-30T16:17:14.150 回答
1

join 有错误的子句

您需要加入 category_id 但在条目表中 category_id 在 entry_cat_id 字段中,因此您可以像这样加入

    SELECT entry.entry_id, entry_category.category_name, entry.entry_name
    FROM entry
    INNER JOIN entry_category
    ON entry.entry_cat_id=entry_category.category_id;
于 2013-05-30T16:18:53.780 回答