Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Join Same Table

Tags:

sql

mysql

I have the table 'meta_data' with the following fields:

  • id
  • post_id
  • meta_key
  • meta_value

I'd like to loop through and display a list of EACH post (post_id) that has an entry for meta_key='abc' but not one for meta_key='def'

Basically, every post that has a meta_key='abc' entry should have a meta_key='def' entry. I want to generate the list so I can add the missing meta_key='def' entries.

like image 376
execv Avatar asked May 13 '12 23:05

execv


People also ask

Can we join same table in MySQL?

The self join is often used to query hierarchical data or to compare a row with other rows within the same table. To perform a self join, you must use table aliases to not repeat the same table name twice in a single query.

Can we join same table twice in MySQL?

As you may know, it is used to join and combine data from two or more tables into one common data set. In this article, I'm going to discuss special types of joins? in which you combine the same table twice—including joining a table to itself, also known as the self join.

Can we use join on same table?

The self-join is a special kind of joins that allow you to join a table to itself using either LEFT JOIN or INNER JOIN clause. You use self-join to create a result set that joins the rows with the other rows within the same table.

Can we join same table twice?

To form a self-join, you specify the same table twice with different table aliases and provide the join predicate after the ON keyword. In this syntax, the table_name is joined to itself using the INNER JOIN clause.


2 Answers

To achieve this you should use the LEFT OUTER JOIN operation joining the same table.

SELECT a.*
FROM meta_data a
LEFT OUTER JOIN meta_data b ON a.post_id = b.post_id AND b.meta_value = 'def'
WHERE 
a.meta_value = 'abc'
AND b.post_id IS null
like image 137
Gratzy Avatar answered Oct 16 '22 17:10

Gratzy


Make an outer (left) join to itself, filtering on those records that don't match by looking for rows with a null id in the joined table:

select t1.* 
from meta_data t1
left join meta_data t2 on t2.post_id = t1.post_id and t2.meta_key='def' 
where t1.meta_key='abc'
and t2.id is null
like image 27
Bohemian Avatar answered Oct 16 '22 15:10

Bohemian