MySQL从搜索结果中获取列名称

时间:2011-07-10 05:36:08

标签: php mysql search

如果我运行这样的事情:

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

我想知道'foo'是否在a,b,c或“a和b”等列中!

有没有办法在MySQL中执行此操作?

4 个答案:

答案 0 :(得分:3)

您可以使用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'

答案 1 :(得分:0)

使用您用于数据库内容的任何内容,您应该能够将该查询的结果放入数组中,它将如下所示:

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

在此之后你可以使用php的in_array函数来查看foo所在的列。

答案 2 :(得分:0)

假设你不希望它们连在一起,这样的东西可以给你你想要的东西

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'

答案 3 :(得分:0)

您可以随时在选择结果中测试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'