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.
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.
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.
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.)
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.
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
"@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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With