0

I have two tables:

This is my posts table:

+-----+----------------+-------------+
| ID  |   post_title   | post_status |
+-----+----------------+-------------+
| 105 | Red Shirt      | active      |
| 106 | Green Shoes    | active      |
| 107 | Blue Hat       | hidden      |
+-----+----------------+-------------+

This is my meta table:

+-----------+------+
| object_id | lang |
+-----------+------+
|       105 | en   |
|       106 | fr   |
|       107 | en   |
+-----------+------+

I am trying to write an SQL query that returns the ID's of all the posts with the post_status of active AND the lang en. With these two tables, there should only be one result (105).

I am having trouble matching the ID to object_id. Any help would be really appreciated, thank you.

somebodysomewhere
  • 1,102
  • 1
  • 13
  • 25

3 Answers3

0
SELECT p.ID
FROM posts p, meta m
WHERE p.ID = m.object_id
AND p.post_status = 'active'
AND m.lang='en'
Dipak
  • 2,248
  • 4
  • 22
  • 55
0

Join the two tables and then specify the conditions:

SELECT posts.ID
FROM posts
INNER JOIN meta ON meta.object_id = posts.id
WHERE posts.post_status = 'active'
  AND meta.lang = 'en'
Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
0

Given that you only want those rows that have records in both tables, you want an INNER JOIN. There is a good post about different join types here: SQL JOIN and different types of JOINs

For your query, you want the following:

SELECT
    PostTbl.ID -- The column(s) you want to select
FROM
    `posts` AS PostTbl -- I prefer aliasing every table so I keep the habit when self joining
INNER JOIN -- Since we want only the rows with records in both tables
    `meta` AS MetaTbl
    ON PostTbl.ID = MetaTbl.object_id -- The conditions on which we want the tables to join
WHERE
    PostTbl.post_status = 'active' -- Post is 'active'
    AND MetaTbl.lang = 'en'; -- Language is 'en'
kchason
  • 2,836
  • 19
  • 25