如何仅使用一个查询从多个表中获取数据?

时间:2019-08-30 06:18:14

标签: mysql sql

我有一个构想问题,不是代码问题,我的数据库中有4个表,QUESTION,INTERESTS,QUESTIONTAG和USER。

我的表格结构:

INTEREST -- id
         -- user
         -- tagparent

QUESTION_TAG -- id
             -- tagparent
             -- tagchild ( unnecessary )
             -- question 

QUESTION -- id
         -- content and when published ( unnecessary )

我想获得由index_order(field)排序的10个问题,这对USER来说很有趣,并且我知道他对使用QUESTION_TAG关联表(链接在问题和标签之间)的那些问题感兴趣。

所以逻辑是这样

request 0 :  SELECT * FROM QUESTION WHERE id = ( results of request 1
- returns many ) ORDER BY index_order LIMIT 0,10

此请求必须返回许多结果:

request 1 : SELECT DISTICNT question FROM question_tag WHERE tagparent
= ( results of request 2 - returns many )

此请求也返回许多结果

request 2 : SELECT tagparent FROM interests WHERE user=9

因此,使用SubQueries并不是真的有用。

我被困住了,希望我只用一个请求就可以找到解决方案,而无需使用后端语言过滤数据。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

可能就是您想要的。

select question.*, distinct question_tag.question, interests.tagparent
from question 
inner join question_tag on question_tag.question = question.id 
inner join interests on interest.tagparent = question_tag.tagparent 
where interests.user = 9