Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Variables, GROUP_CONCAT, and using it later

Tags:

php

mysql

I am storing a hard list of

SELECT @items := GROUP_CONCAT(ID) FROM table_1 ... etc

@items is now a string of numbers: 55,77,99,2038,2844,etc

Later, I try to use it in a where clause as such:

SELECT * FROM table_2 WHERE table_1.ID IN (@items)

This does not work. It seems like it should. I know when I manually pull the data, put it in a variable, then output it it works:

list($x) = SELECT @items := GROUP_CONCAT(ID) FROM table_1 ... etc
$goodResults = SELECT * FROM table_2 WHERE table_1.ID IN ($x)

Any ideas? Thanks.

like image 864
Tickthokk Avatar asked Sep 16 '10 19:09

Tickthokk


People also ask

What does Group_concat do in MySQL?

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. Otherwise, it returns NULL.

Is there a length limit to Group_concat?

I'm using GROUP_CONCAT() in a MySQL query to convert multiple rows into a single string. However, the maximum length of the result of this function is 1024 characters.

What is set Group_concat_max_len?

The group_concat_max_len variable sets the result length in bytes for the GROUP_CONCAT() function to accommodate a potentially long string. (The default group_concat_max_len setting is 1024 bytes.)

What is separator in MySQL?

The SEPARATOR specifies a literal value inserted between values in the group. If you do not specify a separator, the GROUP_CONCAT function uses a comma (,) as the default separator. The GROUP_CONCAT function ignores NULL values. It returns NULL if there was no matching row found or all arguments are NULL values.


2 Answers

You may want to use the FIND_IN_SET() function:

SELECT * FROM table_1 WHERE FIND_IN_SET(id, @items) > 0;

Test case:

CREATE TABLE table_1 (id int, group_id int);
INSERT INTO table_1 VALUES (1, 1);
INSERT INTO table_1 VALUES (2, 1);
INSERT INTO table_1 VALUES (3, 1);
INSERT INTO table_1 VALUES (4, 1);
INSERT INTO table_1 VALUES (5, 1);

SELECT @items := GROUP_CONCAT(id) FROM table_1 GROUP BY group_id;

SELECT * FROM table_1 WHERE FIND_IN_SET(id, @items) > 0;
+------+----------+
| id   | group_id |
+------+----------+
|    1 |        1 |
|    2 |        1 |
|    3 |        1 |
|    4 |        1 |
|    5 |        1 |
+------+----------+
5 rows in set (0.02 sec)

SQL FIDDLE

like image 168
Daniel Vassallo Avatar answered Nov 03 '22 01:11

Daniel Vassallo


"@items is now a string of numbers". The IN clause expects a set.

http://dev.mysql.com/doc/refman/5.1/en/comparison-operators.html#function_in

like image 22
mluebke Avatar answered Nov 02 '22 23:11

mluebke