繁体   English   中英

搜索任何表字段中是否存在变量并获取表字段名称

[英]search if variable exists in any table field and get the table field name

在网页上使用 DOM,我创建了一个这样的变量:

$adres = "Bruinbergstraat 2,Bruinberg,8730 Oedelem";

在 MySql 表中,我有很多记录; 每条记录至少有 1 个地址字段,其他记录有更多地址字段(最多 7 个)。

当我使用此代码查找变量是否存在于任何地址字段中时:

$command = "Select * from alleclubs where (adres1 like '%" . $adres ."%' or adres2 LIKE '%" . $adres ."%' or adres3 LIKE '%" . $adres ."%' or adres4 LIKE '%" . $adres ."%' or adres5 LIKE '%" . $adres ."%' or adres6 LIKE '%" . $adres ."%' or adres7 LIKE '%" . $adres ."%')";

结果是找到 0 条记录。

我该如何解决这个问题,以便获得变量所在列的表字段名称?

要获取与变量匹配的列的表字段名称,您可以执行以下操作 -

"select *
       from (select 
                concat_ws(',',
                    if( adres1 LIKE '%$adres%','adres1',NULL),
                    if( adres2 LIKE '%$adres%','adres2',NULL),
                    if( adres3 LIKE '%$adres%','adres3',NULL),
                    if( adres4 LIKE '%$adres%','adres4',NULL),
                    if( adres5 LIKE '%$adres%','adres5',NULL),
                    if( adres6 LIKE '%$adres%','adres6',NULL),
                    if( adres7 LIKE '%$adres%','adres7',NULL)
                ) as 'matched_column_names',stamnummer
            from alleclubs ) derived_table
where matched_column_names != '' "

然后,当迭代每一行通过PHP,你可以使用explode(),获得每个列名。

注意:您也可以在 MySQL 中使用CASE ,但CASE在匹配时停止。 上面的查询将为您提供与each single row $adres匹配的所有列名。

更新

您可以直接在您的 phpMyAdmin 中使用您的示例Bruinbergstraat 2,Bruinberg,8730 Oedelem ,如下所示 -

select *
       from (select 
                concat_ws(',',
                    if( adres1 LIKE '%Bruinbergstraat 2,Bruinberg,8730 Oedelem%','adres1',NULL),
                    if( adres2 LIKE '%Bruinbergstraat 2,Bruinberg,8730 Oedelem%','adres2',NULL),
                    if( adres3 LIKE '%Bruinbergstraat 2,Bruinberg,8730 Oedelem%','adres3',NULL),
                    if( adres4 LIKE '%Bruinbergstraat 2,Bruinberg,8730 Oedelem%','adres4',NULL),
                    if( adres5 LIKE '%Bruinbergstraat 2,Bruinberg,8730 Oedelem%','adres5',NULL),
                    if( adres6 LIKE '%Bruinbergstraat 2,Bruinberg,8730 Oedelem%','adres6',NULL),
                    if( adres7 LIKE '%Bruinbergstraat 2,Bruinberg,8730 Oedelem%','adres7',NULL)
                ) as 'matched_column_names',stamnummer
            from alleclubs ) derived_table
where matched_column_names != '';

暂无
暂无

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

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