首页 > 解决方案 > 需要从 MySQL 中获取行

问题描述

我在 MySQL DB 的一列中有记录,例如:

ID                           Tax
1                      GST + PST + ABC 
2                      PST + GST + ABC
3                            XYZ
4                      PST + ABC + GST

这些在 DB 中存储为 varchar。通过我的代码,我需要从数据库中获取与 tax = "GST + PST + ABC" 等条件匹配的记录

目前,由于查询,我只获得了第一条记录:

Select * from table where taxes = "GST + PST + ABC";

但是我想从数据库中获取所有记录,其中无论位置如何,都会出现以上 3 个名称(GST、PST、ABC)。

所以,如果我申请上述条件,我需要记录:

GST + PST + ABC 
PST + GST + ABC
PST + ABC + GST

我正在使用 MySQL DB,请告诉我是否有任何功能可以根据我的情况实现上述结果

标签: mysqlsql

解决方案


我会建议这样的事情:

where taxes like '%GST%' and
      taxes like '%PST%' and
      taxes like '%ABC%' and
      length(taxes) = 15;

如果您想要这三个代码,这将测试长度。您还可以测试的数量+

where taxes like '%+%+%' and taxes not like '%+%+%+%'

或者,如果您想要这些代码而不需要其他代码,那么请忽略这些条件。

这假设名称不重叠(因此没有称为“GS”或“ST”的税)。如果有可能:

where concat(' ', taxes, ' ') like '% GST %' and
      concat(' ', taxes, ' ') like '% PST %' and
      concat(' ', taxes, ' ') like '% ABC %';

推荐阅读