php - 如何使用php一次从mysql数据库中获取一个单词

标签 php mysql database

实际上,我已经创建了一个 CMS,我可以在其中插入带有关键字的帖子。我的意思是我在 mysql 数据库中使用一个表,其中有一个名为“关键字”的列。

我想使用以逗号分隔的关键字创建类别,为此我必须一次获取一个词,如果特定帖子有很多词,我想知道我的 sql 查询(或 PHP 代码)必须使用 PHP 来执行此操作。

例如:- 如果我有如下所示的表格,

Post_id post_title post_keywords

1       first post   PHP 
2       second post  PHP, jquery
3       third post   css, html
4       fourth post  html

我想根据关键字创建类别,如下所示:-


PHP -> first post        Jquery ->  second post        CSS -> third post
       second post             

html -> third post
        fourth post

意思是我点击 php 然后它应该包含两个帖子“first post”和“second post”。

最佳答案

你的帖子表:

CREATE TABLE posts
    (`id` int, `title` varchar(11))
;

INSERT INTO posts
    (`id`, `title`) 
VALUES
    (1, 'first post'),
    (2, 'second post'),
    (3, 'third post'),
    (4, 'fourth post')
;

你的标签表

CREATE TABLE tags
    (`id` int, `tag` varchar(6))
;

INSERT INTO tags
    (`id`, `tag`)
VALUES
    (1, 'PHP'),
    (2, 'jquery'),
    (3, 'css'),
    (4, 'html')
; 

还有你的连接表。

CREATE TABLE post2tags
    (`postid` int, `tagid` int)
;

INSERT INTO post2tags
    (`postid`, `tagid`)
VALUES
    (1, 1),
    (2, 1),
    (2, 2),
    (3, 3),
    (3, 4),
    (4, 4)
;

然后这个 SQL 基本上可以得到你想要的(可能顺序不同):

SELECT t.*, p.*
FROM tags t
INNER JOIN post2tags p2t ON t.id=p2t.tagid
INNER JOIN posts p ON p.id=p2t.postid
ORDER BY t.tag, p.title

这是一个 SQLFiddle

这是一个多对多的关系。一旦您理解了它,您可能会经常使用它。

关于php - 如何使用php一次从mysql数据库中获取一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17937667/

相关文章:

database - 查询KDB中的多个表

java - Hibernate @UniqueConstraint 目的

php - 某列分组显示的SQL语句

MySQL 在插入位置后触发更新行

mysql - 2 个嵌套的 COUNT 和 GROUPBY 语句上的 SQL JOIN 错误

java - 如果数据库查询低于 100 毫秒,我应该线程化吗

PHP - chmod 将无法正常工作

php - 如何在不转到 php.ini 文件的情况下禁用 eval 函数?

javascript - 使用 php mysqli 插入 json 数组时出错

php - 在动态内容中,使用 jQuery 完成所有未完成的 html 标签