繁体   English   中英

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

[英]How to fetch one word at a time from mysql database using php

实际上,我已经创建了一个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

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

我会做以下

桌子后

PostId|PostName|...
     1|First Post|...
     2|Second Post|...
       ...

表格关键字

keyID|KeyName
     1|PHP
     2|JQUERY
      ...

表RE_Post_KEY(很多)

PostID|KeyID
     1|1
     1|2
     2|1
     2|2
     ...

虽然我同意规范化数据库的建议,但是要回答您的特定问题,您可以使用FIND_IN_SET()

SELECT Post_Title
FROM YourTable
WHERE FIND_IN_SET('php', post_keywords)

但是,如果您对数据库进行规范化,则只需使用简单的JOIN

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM