{
"accessToken": "",
"groupName": "",
"startLocation": [
36.15, 76.32
],
"rideDate": "",
"coverPic": "file"
}
结果:
SELECT
e.*,
(
SELECT GROUP_CONCAT(topic_name)
FROM topic
WHERE id IN (e.topic_ids)) AS topics
FROM exam e
此查询返回单个主题名称作为结果,但是当我使用它时:
topics = xyz topic
结果:
SELECT
e.*,
(
SELECT GROUP_CONCAT(topic_name)
FROM topic
WHERE id IN (1,4)) AS topics
FROM exam e
工作正常,并且考试表在DB(逗号分隔的主题ids = 1,4)中具有与varchar类型字段相同的值。 字段的数据类型有什么问题吗?
答案 0 :(得分:0)
首先,让我告诉你有关现场CSV的糟糕程度。
| id | topic_ids |
|----|-----------|
| 1 | a,b,c |
| 2 | a,b |
这就是撒旦在关系数据库中的样子。
之后可能是最糟糕的"让列为行,并使用递归连接来恢复所有内容。"
应该如何?
exam
| id |
|----|
| 1 |
| 2 |
exam_topic
| exam_id | topic_id |
|---------|----------|
| 1 | a |
| 1 | b |
| 1 | c |
| 2 | a |
| 2 | b |
topic
| id |
|----|
| a |
| b |
| c |
现在,虽然可能很糟糕,但这是"动态"替代方案,使用FIND_IN_SET()
:
SELECT
e.*,
(
SELECT GROUP_CONCAT(topic_name)
FROM topic
WHERE FIND_IN_SET(id, e.topic_ids) > 0
) AS topics
FROM exam e
MySQL 5.6架构设置:
CREATE TABLE exam
(`id` int, `topic_ids` varchar(5))
;
INSERT INTO exam
(`id`, `topic_ids`)
VALUES
(1, 'a,b,c'),
(2, 'a,b'),
(3, 'b,c,d'),
(4, 'd')
;
CREATE TABLE topic
(`id` varchar(1), `topic_name` varchar(4))
;
INSERT INTO topic
(`id`, `topic_name`)
VALUES
('a', 'topA'),
('b', 'topB'),
('c', 'topC'),
('d', 'topD')
;
查询1 :
SELECT
e.*,
(
SELECT GROUP_CONCAT(topic_name)
FROM topic
WHERE FIND_IN_SET(id, e.topic_ids) > 0
) AS topics
FROM exam e
<强> Results 强>:
| id | topic_ids | topics |
|----|-----------|----------------|
| 1 | a,b,c | topA,topB,topC |
| 2 | a,b | topA,topB |
| 3 | b,c,d | topB,topC,topD |
| 4 | d | topD |