mysql - 从列中选择值为 9 的行

标签 mysql sql

我试图从行记录号为 9 的列中进行选择。这似乎是一项简单的任务,但我无法弄清楚。 这是我迄今为止尝试过的:

SELECT * FROM posts WHERE category = 9 LIMIT 3

还有这个

SELECT * FROM posts WHERE category LIKE '%9%' LIMIT 3

还有一些,但没有返回正确的结果。

更新:

在表帖子中我有

post_id
....
category

类别具有值12等。 我只想在网站上显示类别列中值为 9 的帖子 category=9

更新2:

这是帖子表

CREATE TABLE IF NOT EXISTS `posts` (
`post_id` int(11) NOT NULL AUTO_INCREMENT,
`post_title` varchar(250) NOT NULL,
`post_text` longtext NOT NULL,
`post_author` varchar(20) NOT NULL,
`category` int(4) NOT NULL,
PRIMARY KEY (`post_id`),
KEY `category` (`category`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=13 ;

ALTER TABLE `posts`
ADD CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`category`) REFERENCES `category` (`cat_id`);

例如数据

INSERT INTO `posts` (`post_id`, `post_title`, `post_text`, `post_author`, `category`) VALUES
(1, 'title', 'LOREM IPSUM', 'Athor', 1),

更新3:我尝试使用的完整代码

 require_once 'misc/database.inc.php'; 
    $pdo = Database::connect();
    error_reporting(E_ALL); 
    ini_set('display_errors', 1);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    function truncate($text, $chars = 180) {
            $text = $text." ";
            $text = substr($text,0,$chars);
            $text = substr($text,0,strrpos($text,' '));
            $text = $text." ...";
            return $text;
    }
    $query2 = $pdo->query("SELECT * FROM posts WHERE category = '7' LIMIT 3");
    foreach ($query2 as $row) {
        echo '<li class="col-md-12 col-sm-4"> 
              <div class="single-post">
              <h4>'.$post['post_title'].'</h4>   
              <p>'.truncate($row['post_text']).'</p>
              <a href="#" style="float: right;"> More -></a>
              </div>
              </li>';                
    }                          
    Database::disconnect();

最佳答案

嗯,你在循环中使用 $post['post_title'] (ForEach) 尝试使用 $row->post_title

引用https://ellislab.com/codeIgniter/user-guide/database/results.html

关于mysql - 从列中选择值为 9 的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28631041/

相关文章:

sql - 选择不存在的行

mysql - 您的 SQL 语法 EXTRACT 有误

mysql - 有没有办法优化这个更新查询?

mysql - MySQL 中执行一个 JOIN + 一个 LIKE 语句更快还是执行两个 JOIN 更快?

mysql - 备份MYSQL的应用程序

php - Foreach更新sql循环不创建循环

c# - 从 C# 中的 cmd.Parameters 获取 ReturnValue?

jquery - db查询时如何处理随机字母大小写实例?

php - 如何更快地将csv文件上传到mysql数据库

mysql - MySQL 是否支持内部可变性或粘性位?