hobby_users表:
subcategory_master表:
我的查询:
SELECT hobby_users.user_subcategory_id,GROUP_CONCAT(subcategory_master.subcategory_name) AS subcategory_name
FROM `hobby_users`
INNER JOIN subcategory_master
WHERE hobby_users.hobby_users_id='1' AND subcategory_master.subcategory_master_id IN(SELECT user_subcategory_id FROM `hobby_users` WHERE hobby_users_id='1')
实际结果:
预期结果:
注意:子查询返回1,2
请建议或帮助我错了。
答案 0 :(得分:2)
对于group_concat,您应该使用GROUP BY进行分组
SELECT
hobby_users.user_subcategory_id
,GROUP_CONCAT(subcategory_master.subcategory_name) AS subcategory_name
FROM `hobby_users`
INNER JOIN subcategory_master
WHERE hobby_users.hobby_users_id='1'
AND subcategory_master.subcategory_master_id IN (SELECT user_subcategory_id FROM `hobby_users` WHERE hobby_users_id='1')
GROUP BY hobby_users.user_subcategory_id
答案 1 :(得分:0)
/*
drop table if exists hobby_users;
create table hobby_users(hobby_users_id int, user_name varchar(3), user_subcategory_id varchar(3));
drop table if exists subcategory_master;
create table subcategory_master(subcategory_master_id int, subcategory_name varchar(3));
insert into hobby_users values
(1,'abc','1,2'),
(2,'def','1,3');
insert into subcategory_master values
(1,'aaa'),(2,'bbb'),(3,'ccc'),(4,'ddd');
*/
MariaDB [sandbox]> SELECT h.hobby_users_id,
-> h.user_subcategory_id
-> ,GROUP_CONCAT(sm.subcategory_name) AS subcategory_name
-> FROM `hobby_users` h
-> INNER JOIN subcategory_master sm
-> WHERE h.hobby_users_id='1'
-> AND
-> find_in_set(sm.subcategory_master_id,h.user_subcategory_id) > 0
-> GROUP BY h.user_subcategory_id;
+----------------+---------------------+------------------+
| hobby_users_id | user_subcategory_id | subcategory_name |
+----------------+---------------------+------------------+
| 1 | 1,2 | aaa,bbb |
+----------------+---------------------+------------------+
1 row in set (0.00 sec)