简体   繁体   English

在同一查询中两次使用 INNER JOIN

[英]Using INNER JOIN twice in the same query

I'm still trying to get the hang of SQL. I built 1 query that pulls out thread_id's from a filter_thread(contains 'filter_id' and 'thread_id' columns) table and a filter('filter_id and 'tag') table'我仍在尝试掌握 SQL 的窍门。我构建了 1 个查询,从 filter_thread(包含“filter_id”和“thread_id”列)表和过滤器(“filter_id 和”tag“)表中提取 thread_id”

Then, I use an entirely different query to find the thread table contents, which contains the 'thread_id.'然后,我使用完全不同的查询来查找包含“thread_id”的线程表内容。

I realize this isn't the best way to do it, but can't get a successful query.我意识到这不是最好的方法,但无法获得成功的查询。 Would anyone be able to help?有人能帮忙吗?

$query = "SELECT ft0.thread_id 
FROM filter f0 
INNER JOIN filter_thread ft0 ON ft0.filter_id = f0.filter_id 
WHERE f0.tag LIKE '%filter1%' 
OR f0.tag LIKE '%filter2%'"
$result = $query->result_array();
$thread = array();
foreach ($result as $thread_id)
{
   $id = $thread_id['thread_id'];
   $query = $this->db->query("SELECT * FROM thread WHERE thread_id='$id'");
   $thisRow = $query->result_array();
   array_push($thread, $thisRow[0] );
}

THANKS!谢谢!

You can do it in a single query, like so:您可以在单个查询中执行此操作,如下所示:

SELECT t.*
  FROM filter AS f0
 INNER JOIN filter_thread AS ft0
    ON ft0.filter_id = f0.filter_id
 INNER JOIN thread AS t
    ON ft0.thread_id = t.thread_id
 WHERE f0.tag LIKE '%filter1%'
    OR f0.tag LIKE '%filter2%
select t.x, t.y, ... from thread t
inner join filter f on f.thread_id = t.thread_id
inner join filter_thread ft on ft.filter_id = f.filter_id
where bla bla

With maybe some group by...?也许有一些团体......?

Try this试试这个

SELECT t.*, f0.*
FROM filter f0 
INNER JOIN filter_thread ft0 ON ft0.filter_id = f0.filter_id 
INNER JOIN thread t ON t.thread_id = ft0.thread_id 
WHERE f0.tag LIKE '%filter1%' 
OR f0.tag LIKE '%filter2%'"
GROUP BY f0.filter_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM