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 开发者_如何学Golike to know if the 'foo' was in column a, b, c or "a and b" etc.!
Is there any way to do this in MySQL??
you can use CONCAT_WS and IF , to show in one column the founded columns seperated by comma
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.
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 = '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'
精彩评论