Ben Lobaugh Online

I think, therefore I am. I am, therefore I sail

Tag: mysql

Picture of tables

How to extract a single table from a MySQL sql file

Ever received a large MySQL dump file and only needed one table out of it?

I ran across just this issue. The full database took significant time to import and I only needed a small subsection of the DB, just one single table. Rather than waiting for it all to import, I pulled together a sed command that extracts a single table from the sql file. Check it out:

sed -n ‘/Records of TABLE_NAME/,/Table structure for/p’ FULL_SQL_FILE.sql > table.sql

Replace TABLE_NAME and FULL_SQL_FILE with the names of the table you want and the sql file to pull it from, respectively.

You will now have a table.sql file in your directory that is ready to be imported.

Photo by chuttersnap on Unsplash

Find and update WordPress posts with comments older than NNN days

I have a use case where I need to disable comments on posts in WordPress where the last comment was more than one year, or 365 days, ago.

Posts can be found with this query:

SELECT p.ID, p.post_title, p.post_date, p.comment_status, p.`ping_status`
FROM wp_posts AS p
WHERE p.ID IN (
     SELECT c.comment_post_ID
     FROM wp_comments AS c
     WHERE DATEDIFF( curdate(), c.comment_date ) <= 365
  );

The outer query takes the inner query as the search parameter. The inner query is finding the latest comment for each post based on the number in the WHERE condition. 365 represents 365 days, or 1 year.

Therefore, this query is getting the latest comment for post where the comment is less than 1 year old.

Now let’s say you need to update the posts to disable comments. The goal is to disable commenting for all posts that have not had a comment within the last year. It can be accomplished with the following:

UPDATE wp_posts
SET comment_status='closed', ping_status='closed'
WHERE ID IN (
		SELECT c.comment_post_ID
		FROM wp_comments AS c
		WHERE DATEDIFF( curdate(), c.comment_date ) >= 365
);

Here again the number 365 represents the number of days.

Check the posts and you should see the comments have been closed.