如何在MySQL中用原始数据查找截断数据

62lalag4  于 2023-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(74)

下面是一个数据库结构来说明我的问题

CREATE TABLE `company` (
    `company_id` int(11) NOT NULL, 
    `name` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

当我添加一个名称超过10个字符的公司时,它将被截断。所以当我搜索公司的全名时,我找不到它。

问题:我怎样才能得到« name »列的最大长度(在这个例子中是10),以便能够截断并使用« SUBSTRING()»进行研究

注意:上下文不允许更改名称的最大长度

o2rvlv0m

o2rvlv0m1#

最好的方法是查询information_schema。像这样的东西应该为你工作。

select character_maximum_length 
  from information_schema.columns 
 where table_schema = database()
   and table_name = 'company'
   and column_name = 'name'

你会得到一个你想要的长度的一行结果集。
你可以用一个(nasty!)这样的查询模式。

select company_id, name
  from company
  where name = substring('A long search string', 1, (
                    select character_maximum_length 
                      from information_schema.columns 
                     where table_schema = database()
                       and table_name = 'company'
                       and column_name = 'name') )

或者,您可以尝试使用会话变量来执行这种(可读性更强的)连续查询对。

select @max :=  character_maximum_length 
  from information_schema.columns 
 where table_schema = database()
   and table_name = 'hotels'
   and column_name = 'name' ;

select company_id, name
  from company
  where name = substring('A long search string', 1, @max)
qoefvg9y

qoefvg9y2#

你是说你在搜索类似

SELECT * FROM company WHERE company = LEFT('something longer than 10 chars', 10);

  • LEFT()文档

要获得varchar列的长度,必须查询information_schema。

SELECT character_maximum_length 
FROM information_schema.columns 
WHERE table_schema = 'your_schema'
AND table_name = 'company'
AND column_name = 'name';

所以你的查询变成了

SELECT * 
FROM company 
WHERE company = LEFT('something longer than 10 chars', (
    SELECT character_maximum_length 
    FROM information_schema.columns 
    WHERE table_schema = 'your_schema'
    AND table_name = 'company'
    AND column_name = 'name';
)
);

相关问题