如何从不同的表中选择实体?

时间:2010-09-08 15:24:20

标签: php mysql

我有一个评论系统,我将新闻ID存储在评论表中以引用和从newstable中获取值,我的两个表是这样的。

新表,

CREATE TABLE  `news` (
`id` int(20)  NOT NULL auto_increment,
`timestamp` int(20) NOT NULL,
`title` varchar(255) NOT NULL,
`content` text NULL,
`pic_title` varchar(255) NOT NULL,
`pic_brief` varchar(255) NOT NULL,
`pic_detail` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

评论表

CREATE TABLE `comments` (
`id` int(20) NOT NULL auto_increment,
`timestamp` int(20) NOT NULL,
`title` varchar(255) NOT NULL,
`name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`phone` int(11) NULL,
`location` varchar(50) NOT NULL,
`comment` text NOT NULL,
`approve` tinyint(1) NOT NULL,
`news_id` int(20) NOT NULL,
PRIMARY KEY(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

在评论表的news_id中我存储了新闻的id,我想从评论表中进行选择查询,它应该从参考评论表中的news_id的新闻中选择news.title,

我做了类似的事。

                $query = "SELECT comments.id,
                 comments.timestamp,
                 comments.name,
                 comments.email,
                 comments.phone,
                 comments.location,
                 comments.comment,
                 news.title FROM 
                 comments, news ORDER BY id DESC LIMIT $from, " . COMM_POST_NUMBER;

如何让它仅从news.title中获取标题,引用评论表中的news_id中的ID?

4 个答案:

答案 0 :(得分:1)

$query = 'SELECT comments.*, news.title
            FROM comments
       JOIN LEFT news
              ON news.id = comments.news_id
        ORDER BY id DESC
           LIMIT ' . (int) $from . ', ' . COMM_POST_NUMBER;

答案 1 :(得分:1)

您需要join两个表:

$query = "SELECT comments.id,
         comments.timestamp,
         comments.name,
         comments.email,
         comments.phone,
         comments.location,
         comments.comment,
         news.title
         FROM comments INNER JOIN news ON comments.news_id = news.id
         ORDER BY id DESC LIMIT $from, " . COMM_POST_NUMBER;

另一种表示法是:

FROM comments, news WHERE comments.news_id = news.id

P.S。一定要清理你的输入,不要依赖$from是一个整数,强制它是一个整数:

$from = intval($from);

答案 2 :(得分:0)

在ORDER BY之前需要一个where子句:

... FROM comments, news WHERE comments.news_id = news.id ORDER BY ...

答案 3 :(得分:0)

使用JOIN

SELECT comments.id,
             comments.timestamp,
             comments.name,
             comments.email,
             comments.phone,
             comments.location,
             comments.comment,
             news.title 
FROM 
             comments
join news on news.id=comments.news_id
ORDER BY id DESC 
LIMIT .................