我在开发和生产服务器上运行相同查询时遇到问题。我的应用程序存储会议发言人和会议运行MySQL 5.1的开发服务器正确地仅返回事件会话的相关扬声器,但运行MySQL 5.0.9的生产服务器返回多个不一定与该会话相关联的扬声器。 (注意:我目前无法将生产服务器升级到5.1。)
演讲者表:
+------------+--------------+
| speaker_id | name |
+------------+--------------+
| 100 | John Doe |
| 200 | Steve Rogers |
| 300 | Tony Stark |
+------------+--------------+
会话表:
+------------+------------------+
| session_id | session_speakers |
+------------+------------------+
| 1 | [100] |
| 2 | [100,200] |
| 3 | [300] |
+------------+------------------+
SELECT
s.session_id,
GROUP_CONCAT(DISTINCT sp.name SEPARATOR ' & '),
FROM
sessions s
LEFT JOIN
speakers sp ON INSTR(s.session_speakers, sp.speaker_id)
GROUP BY
s.session_id
session_id = 1的开发服务器结果
'John Doe'
session_id = 1的典型生产服务器结果
'John Doe & Steve Rogers & &'
答案 0 :(得分:1)
您应该规范化表格布局:
speakers
+------------+--------------+
| speaker_id | name |
+------------+--------------+
| 100 | John Doe |
| 200 | Steve Rogers |
| 300 | Tony Stark |
+------------+--------------+
和
sessions_to_speakers
+------------+------------------+
| session_id | session_speakers |
+------------+------------------+
| 1 | 100 |
| 2 | 100 |
| 2 | 200 |
| 3 | 300 |
+------------+------------------+
和
sessions
+------------+--------------+
| session_id | name |
+------------+--------------+
| 1 | Session 1 |
| 2 | Session 2 |
| 3 | Session 3 |
+------------+--------------+
然后你可以使用一个简单的" join"获得所有演讲者:
SELECT * FROM speakers INNER JOIN sessions_to_speakers ON
sessions_to_speakers.session_speakers = speakers.speaker_id
WHERE sessions_to_speakers.session_id = 1;
建议:
修复列名称。如果不是外键,请不要重复表名。即id
表的speaker
应该被称为id
(不 speaker_id
)。仅当从session_to_speaker
表引用时,它应该被称为speaker_id
(对于会话和引用相同)