dongmu1914 2014-03-05 04:50
浏览 25
已采纳

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

I indeed read this post (Get all posts from a specific category) but it does not seem to apply to my situation.

My situation is that i have two tables as follows:

1/ table categories

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';

in which lang_id values are 1 (equivalent to English) and 2 (equivalent to Vietnamese) which is used for filtering by using $_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/ table posts:

    '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';

In which the category_id is the foreign key of the first table.

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

I would like to select the posts in a certain category when we mouse-click on it. So, I run this query:

$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>';
}   

But the result does not return as desired. For example, When I click on category 1 (Arts and Entertainment), the result returns two subjects (arts posted in category_id 1, business and money posted in category_id 5 ).

Can you help me to re-build the query, please? I really really got stuck here.

  • 写回答

2条回答 默认 最新

  • douji2520 2014-03-05 04:59
    关注
    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}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 机器学习简单问题解决
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写