Jump to content

Select Data From A Different Table


frostiecuk

Recommended Posts

Hi all

 

I'm having fun and games (well, not really fun) trying to get a SELECT statement to work on a wordpress website and wondered if anyone out there could help.

 

Basically I am trying to retrieve 10 posts that have an expiry date of today. Selecting 10 posts is fine, the problem start when I try to filter it based on date.

SELECT * FROM wp_posts WHERE post_type = "listing" LIMIT 10

 

However the expiry date is held in a different table;

Table: wp_postmeta

Field: listing_expiry_date

Date: is stored in a column called meta_value (in mm-dd-yyyy format)

 

I suspect the link between wp_posts and wp_postmeta takes place using post_id. Although I know what it is that needs to happen, I'm at a loss as to how to code it correctly;

SELECT * FROM wp_posts WHERE post_type = "listing" WHERE meta_value IN listing_expiry_date in wp_postmeta = TODAY LIMIT 10

 

Can anyone please advise how to go about this?

 

Many thanks

Edited by frostiecuk
Link to comment
Share on other sites

Use a JOIN

 

SELECT *
FROM wp_posts
INNER JOIN wp_postmeta USING (post_id)
WHERE post_type = 'listing' AND listing_expiry_date = '11-29-2012'
LIMIT 10

 

edit

PS. your date format is pretty useless. You should use DATE type fields, format yyyy-mm-dd, which allows for comparisons and sorting and can be used by the inbuilt shedload of mysql datetime functions

Edited by Barand
Link to comment
Share on other sites

Hi Barand

Firstly many thanks. I got an error "Unknown column 'post_id' in 'from clause' but based your suggestion have concocted the following;

SELECT *
FROM wp_posts
INNER JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id
WHERE post_type = 'listing'
AND post_status = 'publish'
AND meta_value = '11-29-2012'
LIMIT 10

 

This works a treat, however now I need the date to be dynamic (i.e. not an actual date, but @Today). I've tried GETDATE TODAY AND CURDATE but nothing seems to return the correct results. Any ideas on this last tweak?

 

Thanks again.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.