使用MySQL连接四个表并从其中两个获取值

时间:2013-09-01 14:34:21

标签: mysql sql

我看了类似的问题,但我找不到合适的语法。

我有这些表格:

行情 - quotes_id - author_id - quote_ENG

作者 - author_id - 作者

TopicMap - topicmap_id - topics_ENG

QuotesByTopic - quotes_id - topicmap_id

我需要从表格引用中获取'quote_ENG',并从表Authors中获取'author',其中'topic_ENG'='age'。

我可以获得'quote_ENG'值...:

SELECT quote_ENG
FROM Quotes, TopicMap, QuotesByTopic
WHERE TopicMap.topics_ENG='age'
  and QuotesByTopic.topicmap_id = TopicMap.topicmap_id
  and QuotesByTopic.quotes_id = Quotes.quotes_id 

...但我错过了获得'作者'价值的最后一段:

SELECT author, quote_ENG
FROM Authors, Quotes, TopicMap, QuotesByTopic
WHERE TopicMap.topics_ENG = 'age'
  and Authors.author_id = Quotes.author_id
  and QuotesByTopic.topicmap_id = TopicMap.topicmap_id
  and QuotesByTopic.quotes_id = Quotes.quotes_id

感谢您的帮助

2 个答案:

答案 0 :(得分:3)

请改为尝试:

SELECT 
  q.quote_ENG,
  a.author
FROM QuotesByTopic  AS qt 
INNER JOIN TopicMap AS t ON qt.topicmap_id = t.topicmap_id
INNER JOIN Quotes   AS q ON qt.quotes_id   = q.quotes_id
INNER JOIN Authors  AS a ON a.author_id    = q.author_id
WHERE t.topics_ENG = 'age'

答案 1 :(得分:0)

编辑:你在我打字的时候改变了你的问题......我仍然会使用一个独特的例子,你想要做一些像tma.topics_ENG IN('年龄','性别')这样的事情。正如另一个人所示,我将使用显式连接。包括你自己在内的每个人都更容易阅读和理解。

SELECT DISTINCT
       ath.author,
       qts.quote_ENG
FROM quotes qts
INNER JOIN Authors ath
    ON qts.author_id = ath.author_id
INNER JOIN QuotesByTopic qbt
    ON qts.quote_id = qbt.quote_id
INNER JOIN TopicMap tma
    ON qbt.topicmap_id = tma.topicmap_id
WHERE tma.topics_ENG = 'age';