mysql - 如何从 SQL 查询中获取前 160 个字符并删除 HTML?

标签 mysql sql sequelpro

我四处寻找是否可以找到直接解决我的问题的解决方案,但我似乎找不到。

我正在查询我的旧数据库并创建一个新表,我可以将其导入到我的新数据库中。我想创建一个名为 news_releases_summary 的新字段,它派生自 news_releases_body,但只包含前 160 个字符(用于 SEO 元描述),最好没有 HTML。

我当前的查询如下所示。我遇到问题的功能是 LTRIM RTRIM - 我什至不确定它是否适合这项工作? * 请注意,我还需要删除\n\t,因为如果我不这样做,最终输出将不会验证为 JSON。

SELECT  
FROM_UNIXTIME(exp_channel_titles.entry_date,'%m/%e/%Y %h:%i %p') AS entry_date,
exp_channel_titles.status, 
exp_channel_titles.title, 
exp_channel_data.field_id_66 AS news_releases_subtitle, 
exp_channel_data.field_id_65 AS news_releases_contact, 
REPLACE(replace(exp_channel_data.field_id_67,char(10),''),char(13),'') AS news_releases_body
LTRIM(RTRIM(REPLACE(replace(exp_channel_data.field_id_67,char(10),''),char(13),''))) AS news_releases_summary
FROM exp_channel_data INNER JOIN exp_channel_titles 
ON exp_channel_data.entry_id = exp_channel_titles.entry_id 
WHERE exp_channel_data.channel_id = '21' 
ORDER BY exp_channel_titles.entry_date

更新

这就是我现在所在的位置,但我收到错误消息“FUNCTION ee_2.strip_tags 不存在”。我应该在查询中直接包含 strip_tags 函数吗?我在 Mac 上使用 Sequel Pro。

CREATE FUNCTION `strip_tags`($str text) RETURNS text
BEGIN
    DECLARE $start, $end INT DEFAULT 1;
    LOOP
        SET $start = LOCATE("<", $str, $start);
        IF (!$start) THEN RETURN $str; END IF;
        SET $end = LOCATE(">", $str, $start);
        IF (!$end) THEN SET $end = $start; END IF;
        SET $str = INSERT($str, $start, $end - $start + 1, "");
    END LOOP;
END;

SELECT  
FROM_UNIXTIME(exp_channel_titles.entry_date,'%m/%e/%Y %h:%i %p') AS entry_date,
exp_channel_titles.status, 
exp_channel_titles.title, 
exp_channel_data.field_id_66 AS news_releases_subtitle, 
exp_channel_data.field_id_65 AS news_releases_contact, 
REPLACE(REPLACE(exp_channel_data.field_id_67,char(10),''),char(13),'') AS news_releases_body,
LEFT(strip_tags(REPLACE(REPLACE(exp_channel_data.field_id_67,char(10),''),char(13),'')),160)     AS news_releases_summary 
FROM exp_channel_data INNER JOIN exp_channel_titles 
ON exp_channel_data.entry_id = exp_channel_titles.entry_id 
WHERE exp_channel_data.channel_id = '21' 
ORDER BY exp_channel_titles.entry_date

最佳答案

您应该能够使用嵌套 replace调用去除不需要的换行符;有questions on stack exchange that deal with this already ,尽管他们使用文字 \n\r 而不是使用 char功能。

对于剥离 HTML 实体,如果不滚动您的函数来完成业务,没有一种简单的方法可以做到这一点。谢天谢地,someone has done that for you as well .

最后,如果您只想在结果中包含 160 个字符,请使用 left函数将结果限制为最左边的 160 个字符。

关于mysql - 如何从 SQL 查询中获取前 160 个字符并删除 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24330536/

相关文章:

sql - 将充满逗号分隔值的 varchar 传递给 SQL Server IN 函数

sql - 如果一个或多个表中可能缺少该键,您能否在同一个键上连接三个表?

java - 如何解决 java.lang.ClassCastException : hibernate

MySql 多表与单表 : performance

mysql - 创建mysql存储过程时出现1193错误

mysql - 如何在 Sequel Pro TEXT 编辑器中创建 JSON 字符串?

mysql - Sequel Pro 连接 mysql 服务器

mysql - 如何在 mysql 中加载 geonames.org 数据集

mysql - 帮我保存我的数据库

java - 在 Java 中为 MySQL 转义字符串