【问题标题】:PHP MySQL Merge Resulting Query Rows into Single ColumnPHP MySQL将结果查询行合并到单列中
【发布时间】:2017-09-18 23:05:48
【问题描述】:

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

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

然后,我将返回其中任何一列匹配的所有行。我需要将这些结果写入一个有两列的新数据库表中。第一列将是正在搜索的代码,在本例中为“23”,第二列将是从我的查询中找到的不是 23 的任何匹配结果。

所以如果我的代码表中的一行看起来像这样...

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

我的新表格会这样格式化,

queriedcode|result
23         | 27
23         | 30
23         | 45

是否有一个 MySQL 查询可以用来实现这一点,或者我最好的选择是使用 PHP,我似乎找不到一个合理的方法来完成我想要使用的。到目前为止,我想出的一切似乎要么不起作用,要么过于复杂,很容易失败。

【问题讨论】:

  • schema 规范化不好,查询使用困难:essentialsql.com/…
  • 你在table codetable中有没有primary kay,比如id等?
  • 是的,“id”是我的主键。
  • 我必须同意 Sammitch:您的代码列似乎包含等效值。这些列可能应该被规范化。 Gordon Linoff 给出的答案清楚地说明了原因。如果您对此有困难,请询问,但请提供您真实且完整的架构。

标签: php mysql sql


【解决方案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 ;

【讨论】:

    猜你喜欢
    • 2010-11-12
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 2012-04-23
    • 2011-06-16
    • 1970-01-01
    • 2017-03-24
    • 2013-07-31
    相关资源
    最近更新 更多