简体   繁体   English

MySQL 从搜索结果中获取列名

[英]MySQL get the columns names from search results

If I run something like this:如果我运行这样的东西:

SELECT * FROM my_table WHERE a = 'foo' OR b = 'foo' OR c = 'foo'

I would like to know if the 'foo' was in column a, b, c or "a and b" etc.!我想知道“foo”是否在 a、b、c 或“a 和 b”等列中!

Is there any way to do this in MySQL?? MySQL 有什么办法吗?

you can use CONCAT_WS and IF , to show in one column the founded columns seperated by comma您可以使用CONCAT_WSIF在一列中显示由逗号分隔的已建立的列

SELECT *,
CONCAT_WS(',',(IF(a = 'foo','a',NULL)) ,(IF( b = 'foo','b',NULL)) ,(IF(c = 'foo','c',NULL)))
AS WhereFound
FROM my_table WHERE a = 'foo' OR b = 'foo' OR c = 'foo'

Using whatever you use for database stuff, you should be able to put the result of that query into an array, it'll look like this:使用您用于数据库的任何内容,您应该能够将该查询的结果放入一个数组中,它看起来像这样:

$row['a']
$row['b']
$row['c']

After this you can use php's in_array function to see which columns foo was in.在此之后,您可以使用 php 的in_array function 查看 foo 所在的列。

Supposing you don't want them concatenated, something like this could give you what you want假设您不希望将它们连接起来,这样的事情可能会给您想要的东西

SELECT IF(a = 'foo', 'Yes','No') AS Was_In_A,
IF(b = 'foo', 'Yes','No') AS  Was_In_B,
IF(c = 'foo', 'Yes','No') AS Was_In_C
FROM my_table WHERE a = 'foo' OR b = 'foo' OR c = 'foo'

You can always test the values of a, b, and c in the select results, but maybe this will make things easier?您始终可以在 select 结果中测试 a、b 和 c 的值,但这也许会使事情变得更容易?

SELECT (a = 'foo') as FooInA, (b = 'foo') as FooInB, 
       (a = 'foo') AND (b = 'foo') as FooInAandB 
FROM my_table WHERE a = 'foo' OR b = 'foo' OR c = 'foo'

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

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