考慮すべきポイントのカップル:
13.5 Prepared SQL Statement Syntaxを使用してオプション:
mysql> DROP TABLE IF EXISTS `my_table`, `customers`;
Query OK, 0 rows affected (0.00 sec)
mysql> DROP FUNCTION IF EXISTS `Get_customerCodes`;
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE IF NOT EXISTS `customers`(
-> `customer_id` INT NOT NULL,
-> `customer_code` VARCHAR(2),
-> PRIMARY KEY(`customer_id`, `customer_code`)
->);
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE IF NOT EXISTS `my_table`(
-> `id` INT NOT NULL,
-> `customer_code` VARCHAR(2)
->);
Query OK, 0 rows affected (0.01 sec)
mysql> CREATE FUNCTION `Get_customerCodes`(`_customer_id` INT)
-> RETURNS VARCHAR(500) CHARSET utf8
-> RETURN (
-> SELECT GROUP_CONCAT(CONCAT('\'', `customer_code`, '\'')
-> SEPARATOR ',')
-> FROM `customers`
-> WHERE `customer_id` IN (`_customer_id`)
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO `customers`
-> (`customer_id`, `customer_code`)
-> VALUES
-> (1002, 1), (1002, 2),
-> (1002, 3), (1002, 4);
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> INSERT INTO `my_table`
-> (`id`, `customer_code`)
-> VALUES
-> (1, 1), (2, 2),
-> (3, 3), (4, 4);
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> SET @`query` := CONCAT('
'> SELECT *
'> FROM `my_table`
'> WHERE `customer_code` IN (',
-> `Get_customerCodes`(CAST('1002' AS SIGNED)), ')');
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @`query` `to_execute`;
+----------------------------------------------------------------------+
| to_execute |
+----------------------------------------------------------------------+
|
SELECT *
FROM `my_table`
WHERE `customer_code` IN ('1','2','3','4') |
+----------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> PREPARE `stmt` FROM @`query`;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE `stmt`;
+----+---------------+
| id | customer_code |
+----+---------------+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
+----+---------------+
4 rows in set (0.00 sec)
mysql> DEALLOCATE PREPARE `stmt`;
Query OK, 0 rows affected (0.00 sec)
はdb-fiddleを参照してください。
'RETURNS varchar(500)<>宣言結果VARCHAR(1000);'注意、結果が切り捨てられる可能性があります。 [13.5 SQL文の準備構文](https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html)を使用することができます。 – wchiquito