Select 列名称基于使用 MYSQL 查询的用户条目

Select column(s) names based on user entry with a MYSQL query

使用 PHP 安全用户将输入参考(例如 NB093019),将使用查询来确定哪些 PO 具有该参考以及它们是否有任何数量。问题是我们有 86 列来检查 Ref 是否在其中,然后一旦找到它所在的列如何检查包含该数量的相应列(table 无法编辑)。

我可以在 PHP 中使用 86 个 if else 语句,然后在每个 PHP 语句中使用更多 if else 语句。进行初始查询后,我没有启动点。

select 'remainder'as prefix, po,  *comments,*GuideRef, *Qty
from remainder 
where  ('NB092419')IN (NWANTcomments,NWANTGuideRef,NWANTpreviouscomments,
                        NWANTpreviousGuideRef,NWANTprevious2comments,
                        NWANTprevious2GuideRef, BPrev2GuideRef, 
                        BPrev2comments, BPrevGuideRef, BPrevcomments, 
                        aGuideRef, Mcomments,MGuideRef,acomments,
                        MAGuideRef,BOGuideRef ) 
group by po

我删除了一些 in() 信息,因此 *comments、*GuideRef、*Qty 也不会太长,这将由 IN() 语句中的哪一列决定 returns 信息。这甚至可能

你也许可以写一个 SQL 写一个 SQL:

 select REPLACE(
   'SELECT ''{colstub}GuideRef'' as which, {colstub}Qty FROM remainder WHERE {colstub}Ref like ''%somevalue%'' UNION ALL',
   '{colstub}',
   REPLACE(column_name, 'GuideRef', '')
 )  
 FROM information_schema.columns 
 WHERE table_name = 'remainder' and column_name LIKE '%Ref'

它的工作方式类似于 "pull all the column names out of the info schema where the column name is like %guideref, replace guideref with nothing to get just the fragment of the column name that is varied: NWANTguideref -> NWANT, NWANTpreviousguideref -> NWANTprevious ... then uses this stub to form a query that gives a string depicting the column name, the qty from the quantity column, where the relevant guideref column is LIKE some value"

如果你 运行 这将产生如下结果集:

SELECT 'aGuideRef' as which, aQty FROM table WHERE aGuideRef LIKE '%lookingfor%' UNION ALL 
SELECT 'bGuideRef' as which, bQty FROM table WHERE bGuideRef LIKE '%lookingfor% ...

所以它基本上输出了一大堆本身就是 SQL 的字符串。它可能需要一些微调,希望您的所有列都可靠且严格地像 xQty, xGuideRef, xComments 三元组,但它实际上为您编写了大部分查询

如果您随后将结果集从结果网格中复制出来并将其粘贴回查询 window,删除最后一个 UNION ALL 并 运行 它,它将搜索列并告诉你在哪里找到它以及数量

它不太适合生产系统,但您可以在 php- 运行 查询中执行相同的操作,将字符串放入另一个 sql 命令,重新 运行它..

我建议您考虑更改 table 结构:

前缀、数量、指南、评论

你不应该有 86 个几乎相同的列;你应该有一列是 86/3 不同值之一,然后你可以查询 guideref 和类型。如果这是一个地址 table,我是说你**不应该*拥有 HomeZipcode、WorkZipcode、UniversityZipcode、MomZipcode、DadZipcode.. 每次你想存储另一种地址时,你都会添加更多列(男朋友邮政编码、女朋友邮政编码、儿童 1 邮政编码...)。相反,如果您只有一个 "addresstype" 列,那么您可以存储任意数量的不同类型的地址,而无需重新编译您的应用程序和更改您的数据库模式

你可以使用这种技术来重塑 table - 写一个 SQL 来写一堆 UNION ALL sqls(没有 WHERE 子句),其中一个列应该是 "recordtype" 列(来自 colstub),其他列应该只是 "qty"、"guide"、"comments"。一旦你有了联合的结果集,你就可以制作一个 table 来保存这 4 个东西,然后将 INSERT INTO newtable 放在联合块的头部