Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Concatenate entire result sets in MySQL?

Tags:

I'm trying out the following query:

SELECT A,B,C FROM table WHERE field LIKE 'query%'
UNION
SELECT A,B,C FROM table WHERE field LIKE '%query'
UNION
SELECT A,B,C FROM table WHERE field LIKE '%query%'
GROUP BY B ORDER BY B ASC LIMIT 5

That's three queries stuck together, kinda sorta. However, the result set that comes back reflects results from query #3 before the results from query #1 which is undesired.

Is there any way to prioritize these so that results come as all for query #1, then all for query #2 then all for query #3? I don't want to do this in PHP just yet (not to mention having to control for results that showed up in the first query not to show in the second and so forth).

like image 419
mauriciopastrana Avatar asked Aug 06 '08 18:08

mauriciopastrana


People also ask

Can I concatenate multiple MySQL rows into one field?

The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value.

Which MySQL function is used to concatenate string?

CONCAT() function in MySQL is used to concatenating the given arguments. It may have one or more arguments. If all arguments are nonbinary strings, the result is a nonbinary string. If the arguments include any binary strings, the result is a binary string.

How concatenate MySQL in SQL?

MySQL CONCAT() Function The CONCAT() function adds two or more expressions together. Note: Also look at the CONCAT_WS() function.


1 Answers

Maybe you should try including a fourth column, stating the table it came from, and then order and group by it:

SELECT A,B,C, "query 1" as origin FROM table WHERE field LIKE 'query%'
UNION
SELECT A,B,C, "query 2" as origin FROM table WHERE field LIKE '%query'
UNION
SELECT A,B,C, "query 3" as origin FROM table WHERE field LIKE '%query%'
GROUP BY origin, B ORDER BY origin, B ASC LIMIT 5
like image 105
Mario Marinato Avatar answered Sep 19 '22 08:09

Mario Marinato