snippetsqlMajor
MySQL - How to check for a value in all columns
Viewed 0 times
columnsallvaluemysqlforhowcheck
Problem
I am curious, is there a good way to search all columns for a given value? For my purposes, it doesn't need to be at all fast, it's just a 1-off kinda thing, and I don't really want to have to type out every field name. That's precisely what I'll be doing for now, but I think surely there's a better way.
I would like to turn this:
into this:
...or, even better (though I seriously doubt it...)
I found this, which seems kinda-not-really close, but I'm not finding anything closer:
Difference being, that searches a selection of columns for the specified values, whereas I'm trying to search ALL columns for a single value.
It's not important though, like I said more than anything I'm just curious
I would like to turn this:
SELECT * FROM table WHERE col1 = 'val' OR col2 = 'val' OR col3 = 'val';into this:
SELECT * FROM table WHERE * = 'val'...or, even better (though I seriously doubt it...)
SELECT * FROM table WHERE * like '%val%'I found this, which seems kinda-not-really close, but I'm not finding anything closer:
SELECT whatever WHERE col1,col2 IN ((val1, val2), (val1, val2), ...)Difference being, that searches a selection of columns for the specified values, whereas I'm trying to search ALL columns for a single value.
It's not important though, like I said more than anything I'm just curious
Solution
SQL doesn't provide a good way of doing this because it's probably not a good table design to have N columns that might have values in the same domain. This is potentially a case of "repeating groups" like if you have columns
If you have a number of columns that have the same logical domain of values, it could be a case where it's a multi-valued attribute (like the phones example). The standard way of storing multi-valued attributes is as multiple rows in another table, with a reference to the row they belong to in the primary table.
If you do that, then you only have to search for the specific value in one column of the dependent table.
phone1, phone2, phone3, ... phoneN.If you have a number of columns that have the same logical domain of values, it could be a case where it's a multi-valued attribute (like the phones example). The standard way of storing multi-valued attributes is as multiple rows in another table, with a reference to the row they belong to in the primary table.
If you do that, then you only have to search for the specific value in one column of the dependent table.
SELECT t.* FROM mytable AS t
JOIN phones AS p ON t.primaryKey = p.refKey
WHERE p.phone = ?Code Snippets
SELECT t.* FROM mytable AS t
JOIN phones AS p ON t.primaryKey = p.refKey
WHERE p.phone = ?Context
StackExchange Database Administrators Q#248830, answer score: 27
Revisions (0)
No revisions yet.