dqhgjay5753 2017-09-18 23:05
浏览 51

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

If I have a database table with columns such as code1, code2, code3, and code4. Then I run the following query against this table.

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

I am then returned all the rows where any one of those columns has a match. I need to take these results and write them into a new database table where there is two columns. First column will be the code being searched for or in this case "23", the second column will be any matching results found from my query that are not 23.

So if a row in my codetable looks like this...

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

My new table will be formatted like this,

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

Is there a MySQL query that can be used to achieve this or would my best bet be to use PHP, I can't seem to find a reasonable method to accomplish what I want using either. Everything I've come up with so far seems to either not work or be so over complicated it could fail easily.

  • 写回答

1条回答 默认 最新

  • duanou2016 2017-09-18 23:20
    关注

    It is probably more efficient to do this in PHP. But, you can do:

    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 ;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程