鍍金池/ 問答/數(shù)據(jù)庫/ mysql where in (select ids_str from test

mysql where in (select ids_str from test)如何查詢

mysql> desc test1
    -> ;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int(11) unsigned | NO   | PRI | NULL    | auto_increment |
+-------+------------------+------+-----+---------+----------------+
mysql> desc test2;
+---------+------------------+------+-----+---------+----------------+
| Field   | Type             | Null | Key | Default | Extra          |
+---------+------------------+------+-----+---------+----------------+
| id      | int(11) unsigned | NO   | PRI | NULL    | auto_increment |
| ids_str | varchar(32)      | YES  |     | NULL    |                |
+---------+------------------+------+-----+---------+----------------+

ids_str是一個字符串。
ids_str="1,2,3"

select * from test1 where id in (select ids_str from test2)
即:

select * from test1 where id in ("1,2,3")

回答
編輯回答
深記你

select * from test1 where find_in_set(id,(select ids_str from test2));

2017年12月18日 19:34
編輯回答
心上人

你的id是int(11),而ids_str是varchar(32),當然就不行。除非把ids_str也改成int型

2017年5月29日 01:18
編輯回答
涼薄

先考慮"1,2,3"轉(zhuǎn)成int類型等于多少

2017年3月8日 14:48
編輯回答
呆萌傻

其實問題的根源就在于怎么把字符串'1,2,3',分隔成mysql的列,即:

ids
1
2
3

有兩種方式

1.自定義函數(shù)(推薦)
2.用這個sql

SELECT substring_index(substring_index(t.ids,',', b.help_topic_id + 1), ',', -1) FROM t_ids t 
join mysql.help_topic b ON b.help_topic_id <  (LENGTH(t.ids) - LENGTH(REPLACE(t.ids, ',', '')) + 1);  

其中t_ids表,就是你問題中test2的設(shè)定

CREATE TABLE `t_ids` (
  `ids` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2018年5月11日 04:18