按照上一个问题(How to do this query in Mysql?)
假设我有一条消息:
Id: 1, Message: This is a message
2个科目:
Id:1, Subject: Math
Id:2, Subject: Science
Id:3, Subject: Numbers
还有2个message_subject_rel条目:
Id: 1, message_id: 1, subject_id: 1
Id: 2, message_id: 1, subject_id: 2
Id: 3, message_id: 1, subject_id: 3
我想进行一个查询,选择将Math AND Science作为我最终使用的主题的消息:
SELECT m.*
FROM messages m
JOIN message_subject_rel ms1 ON (m.id = ms1.message_id)
JOIN subjects s1 ON (ms1.subject_id = s1.id AND s1.subject = 'Math')
JOIN message_subject_rel ms2 ON (m.id = ms1.message_id)
JOIN subjects s2 ON (ms2.subject_id = s2.id AND s2.subject = 'Science');
现在,非常清楚我想要显示消息(因为它确实有这2个主题)并告诉用户它不仅仅有那2个主题,但它实际上有3个,而且不仅那...我想打印3个主题(当然我有很多信息,并且想要实际列出它们,只需1个查询就可以看到它们各自的主题)。我似乎无法理解,如果只有一个查询实际上是可行的,因为我会将n“subject”字段作为返回。
任何想法是否可以只用一个查询来完成,如果是,怎么做?
TY
答案 0 :(得分:2)
有关一种解决方案,请参阅GROUP_CONCAT。但是,我不知道这种方法的效率如何。
select message.Id as id, Message, group_concat(Subject separator ';') as subjects
from message,subject,message_subject_rel
where message.Id=message_subject_rel.message_id
and subject.Id=message_subject_rel.subject_id
group by message.Id
having subjects like '%Math%' and subjects like '%Science%';
由此,我得到:
+------+---------+----------------------+
| id | Message | subjects |
+------+---------+----------------------+
| 1 | Message | Math;Science;Numbers |
+------+---------+----------------------+
显然,你可以做得比我的好';'分隔符和我喜欢的条款。
答案 1 :(得分:0)
您是否尝试过GROUP_CONCAT
?