I really just can't seem to grasb the sytanx of SQL Joins, etc ... so I'm needing some help with this (which I think is quite simple)
I'm querying bid_tag
as follows:
SELECT paid_date, term, pet_id FROM bid_tag WHERE active = 1
And I need to use the pet_id
to then grab some information from another table wp_postmeta
, where the table is actually in a meta_key
meta_value
structure (WordPress) ...
So I need to grab the meta_value
of meta_key
"bid_name", for example... amongst other values.
TABLE
id | meta_key | meta_value
1 bid_name Max
That ID
is the same ID
that I need to connect the initial table to...
I really appreciate it!
Join on both the id
and the meta_key
to select your desired value. If you want values that go with other keys in the meta table as well, one way is to join multiple times:
SELECT bt.paid_date, bt.term, bt.pet_id,
bn.meta_value as bidname,
bo.meta_value as bidother
FROM bid_tag bt
INNER JOIN wp_postmeta bn on bn.id = bt.pet_id and bn.meta_key = 'bid_name'
INNER JOIN wp_postmeta bo on bo.id = bt.pet_id and bo.meta_key = 'bid_other'
WHERE bt.active = 1
If the values won't necessarily be present in the meta table, use a LEFT OUTER JOIN
instead and it will return null
for whatever is missing.
Here's how your query would go:
SELECT B.meta_key, B.meta_value, A.pet_id
FROM bid_tag A
JOIN wp_postmeta B
ON B.id = A.pet_id;
there're some ways to use join:
1)use inner join
or equally just join
:
select
--some columns
from bid_tag
join wp_postmeta on
bid_tag.pet_id = wp_postmeta.id
where
wp_postmeta.meta_key = 'bid_name'
The result will have only that records which pet_id
exists in wp_postmeta
. The other will be omitted. And if wp_postmeta
have a couple of records with the same id
(and exists pet_id
equal this id
) then you'll get a couple records with this pet_id ( BUT with different meta_key
and meta_value
).
2)use left join
:
select
--some columns
from bid_tag
left join wp_postmeta on
bid_tag.pet_id = wp_postmeta.id
where
wp_postmeta.meta_key = 'bid_name'
In this case behavior will be the same except one thing - even if there aren't any id
for a pet_id
the result will contain record from wp_postmeta
with this pet_id
. But meta_key
and meta_value
in this case will be null
.
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.