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.
SELECT p.ID
FROM posts p, meta m
WHERE p.ID = m.object_id
AND p.post_status = 'active'
AND m.lang='en'
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'
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'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.