Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using INNER JOIN twice in the same query

Tags:

php

mysql

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'

Then, I use an entirely different query to find the thread table contents, which contains the '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!

like image 267
Ricky Mason Avatar asked Dec 28 '22 03:12

Ricky Mason


2 Answers

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%
like image 136
gonsalu Avatar answered Jan 09 '23 14:01

gonsalu


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...?

like image 29
Raphaël Althaus Avatar answered Jan 09 '23 15:01

Raphaël Althaus