PHP MySQL将导致的查询行合并为单列

时间:2017-09-18 23:05:49

标签: php mysql sql

如果我有一个包含code1,code2,code3和code4等列的数据库表。然后我对这个表运行以下查询。

VectorTop

然后我返回其中任何一列都匹配的所有行。我需要获取这些结果并将它们写入一个新的数据库表,其中有两列。第一列将是要搜索的代码,或者在这种情况下" 23",第二列将是从我的查询中找到的非23的匹配结果。

因此,如果我的代码表中的一行看起来像这样......

SELECT * 
FROM codetable 
WHERE code1 = 23 OR code2 = 23 OR code3 = 23 OR code4 = 23

我的新表格格式如下,

code1|code2|code3|code4
23   |27   |30   |45

是否有可用于实现此目的的MySQL查询,或者我最好的选择是使用PHP,我似乎无法找到合理的方法来实现我想要的任何一种。到目前为止,我提出的所有内容似乎都不起作用或者过于复杂,它可能很容易失败。

1 个答案:

答案 0 :(得分:1)

在PHP中执行此操作可能更有效。但是,你可以这样做:

select code1 as queriedcode, code2 as result from t where code1 = 23 union all
select code1, code3 from t where code1 = 23 union all
select code1, code4 from t where code1 = 23 union all
select code2, code1 from t where code2 = 23 union all
select code2, code3 from t where code2 = 23 union all
select code2, code4 from t where code2 = 23 union all
select code3, code1 from t where code3 = 23 union all
select code3, code2 from t where code3 = 23 union all
select code3, code4 from t where code3 = 23 union all
select code4, code1 from t where code4 = 23 union all
select code4, code2 from t where code4 = 23 union all
select code4, code3 from t where code4 = 23 ;