选择特定类别中的所有帖子

时间:2014-03-05 04:50:52

标签: php

我确实读过这篇文章(Get all posts from a specific category),但它似乎并不适用于我的情况。

我的情况是我有两张表如下:

1 /表类别

category_id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT,
lang_id TINYINT UNSIGNED NOT NULL,
name VARCHAR(60) NOT NULL,
PRIMARY KEY (category_id),
UNIQUE (name)
         ) ENGINE = INNODB';

其中lang_id值为1(相当于英语)和2(相当于越南语),用于使用$ _SESSION ['lid']进行过滤。

category_id     lang_id         name
  1                 1           Arts and Entertainment
  2                 1           Computers
  3                 2           Nghệ thuật và Giải trí
  4                 2           Máy tính

2 /表格帖子:

    'CREATE TABLE posts (
    post_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    category_id TINYINT UNSIGNED NOT NULL,      
    lang_id TINYINT(3) UNSIGNED NOT NULL,
    user_id INT UNSIGNED NOT NULL,
    subject VARCHAR(150) NOT NULL,
    PRIMARY KEY (post_id),
    INDEX (category_id),
    INDEX (lang_id),
    INDEX (user_id)
    ) ENGINE = MYISAM';

其中category_id是第一个表的外键。

question_id     category_id     lang_id     user_id     subject
  1               1               1                1      arts  
  2               4               2                1      máy tính 
  3               5               1                1      business and money

当我们点击鼠标时,我想选择特定类别的帖子。所以,我运行这个查询:

$q = "SELECT subject
FROM categories AS ca
INNER JOIN questions AS q
USING (category_id)
WHERE q.lang_id = {$_SESSION['lid']}  
GROUP BY ca.category_id

$r = mysqli_query($database_connect, $q)
if(mysqli_num_rows($r) > 0) {
    while ($subject = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
       echo '<ul>
        <li>'. $subject['subject']. '</li>
         </ul>';
}   

但结果并未按预期返回。例如,当我点击类别1(艺术和娱乐)时,结果返回两个主题(在category_id 1中发布的艺术,在category_id 5中发布的商业和金钱)。

请问您能帮我重新构建查询吗?我真的被困在这里了。

2 个答案:

答案 0 :(得分:2)

在WHERE子句中添加类别ID以选择给定类别的帖子

SELECT subject
FROM categories AS ca
INNER JOIN questions AS q
USING (category_id)
WHERE q.lang_id = {$_SESSION['lid']}  
AND ca.category_id = 1

答案 1 :(得分:0)

SELECT categories.*, posts.* from posts left join posts on categories.category_id=posts.category_id where posts.lang_id = {$_SESSION['lid']} and posts.category_id={your given category}