mySQL:当meta_key不存在时将其插入表中

时间:2013-06-15 05:18:59

标签: mysql sql wordpress select insert

好的我正在寻找针对Wordpress数据库在mySQL中运行循环查询。某些记录具有[城市名称]的自定义字段(例如:meta_key ='sidebar'& meta_value ='chicago')。问题是有些人有这个自定义字段而其他人没有。我已经隔离了不通过以下查询的记录:

SELECT object_id 
FROM wp_term_relationships 
WHERE term_taxonomy_id = (
    SELECT term_id FROM wp_terms 
    WHERE name = 'Chicago') 
  AND object_id > 5911

生成的object_id集合需要

INSERT INTO wp_postmeta (meta_key, meta_value,post_id) 
VALUES ('sidebar','chicago',[object_id])

所以我的问题是如何组合这些,所以SELECT循环运行INSERT为每个object_id结果。任何想法将不胜感激。谢谢 -

2 个答案:

答案 0 :(得分:2)

你可以尝试

INSERT INTO wp_postmeta (meta_key, meta_value,post_id)
SELECT 'sidebar','chicago', object_id 
  FROM wp_term_relationships 
 WHERE term_taxonomy_id = 
       (
          SELECT term_id 
            FROM wp_terms 
           WHERE name = 'Chicago'
       ) 
   AND object_id > 5911

答案 1 :(得分:0)

您的解决方案就在这里......

 import java.sql.*;
   public class sample 
  {
public static void main(String[] args) {

 try{

    Class.forName("com.mysql.jdbc.Driver");
    Connection  c=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
    Statement s=c.createStatement();
    Statement dbInsert = c.createStatement();
    ResultSet r=s.executeQuery("SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id = (SELECT term_id FROM wp_terms WHERE name = 'Chicago') AND object_id > 5911");
   while(r.next())
   {

      dbInsert.executeUpdate("INSERT INTO wp_postmeta (meta_key, meta_value,post_id) VALUES ('sidebar','chicago','"+r.getInt("object_id")+"'");

   }


  }
  catch(Exception e)
  {
      System.out.println(e.getMessage());
  }
 }
 }