Fetch only the first match in a query with ordering precedents?
I have a table with field ids (primary key), name1, name2 and nicknames.
Given a name, I want it to return a record containing that name in any of the three fields; however, I want it to only return one record, and sometimes a query that returns more than one match for me. Also, if there are multiple matches, I want it to first return the name that is the same as name1.
This is the query I have now that just gives me everything:
SELECT * FROM table WHERE name1 like "Bob" OR name2 like "Bob" OR nicknames rlike "[,]Bob[,]|[,]Bob$";
Thanks. I am doing this in C ++ and mysql ++.
+1
a source to share
1 answer
SELECT * FROM (
SELECT * FROM table WHERE name1 like "Bob" limit 1
UNION SELECT * FROM table WHERE name2 like "Bob" limit 1
UNION SELECT * from table WHERE nicknames rlike "[,]Bob[,]|[,]Bob$" limit 1
) AS t1 LIMIT 1;
The limit of 1 on each one holds the database to pull Bob's 50,000 records to show you one of them.
+4
a source to share