INNER JOIN的SQL语法问题

时间:2013-02-28 01:52:06

标签: mysql join

我在MySql中有三个表。表1包含以下字段

表1:

EventType
-etid
-description

表2:

EventAsks
-etid
-qid

表3:

Questions
-qid
-textofquestion

如果我有特定的etid,我想找到该事件要求的所有问题。所以给出以下表格......

EventType
etid     description
1        hiking
2        biking


EventAsks
etid      qid
1         1
1         3
2         2
2         3

Questions
qid   textofquestion
1     Is it fun?
2     Is it lots of exercise
3     Is it expensive

所以给定的etid的结果说etid = 1,我想与etid = 1相关的问题返回...

Result
Is it fun?
Is it expensive?

我确信这与加入有关,但我不确切知道如何做到这一点?有什么建议吗?

2 个答案:

答案 0 :(得分:3)

经典 n-to-n 关系:

SELECT Questions.textofquestion FROM EventType
LEFT JOIN EventAsks ON EventAsks.etid = EventType.etid
LEFT JOIN Questions ON Questions.quid = EventAsks.qid
WHERE EventType.etid = 1;

答案 1 :(得分:2)

你可以这样做:

SELECT Questions.textofquestion
FROM EventType
   INNER JOIN EventAsks 
        ON EventType.etid = EventAsks.etid
   INNER JOIN Questions 
        ON EventAsks.qid = Questions.qid
WHERE EventType.etid = 1

由于您已经拥有etid=1,因此可以简化为:

SELECT Questions.textofquestion
FROM EventAsks 
   INNER JOIN Questions 
        ON EventAsks.qid = Questions.qid
WHERE EventAsks.etid = 1