简体   繁体   中英

MYSQL query check if ID exist and copy column row values to another table related column names

I am trying to save Mysql row data from one database table and copy values in new database table via PhpMyAdmin but there is an issue.

My lack of knowledge is result for asking advanced users for help here. Copy, join, merge, delete or else:D..i am really not sure what is the best method to solve this.

TABLE 1 (old) has columns: id, product_id, identifier, content

  • id - we dont need it for this query
  • post_id - (INT) which is actually related to ID in TABLE 2
  • identifier - (VARCHAR) different row values such as quantity, color, discount, price1, price2 which are repeatable fields
  • content - *(LONGTEXT) content

    表格1

TABLE 2 (new) has columns:

  • id - (INT)
  • quantity - (VARCHAR)
  • color - (VARCHAR)
  • discount - (VARCHAR)
  • price1 - (VARCHAR)
  • price2 - (VARCHAR)

I need to check with mysql query does id in TABLE 2 exist compared with post_id from TABLE 1.

If does not exist skip to another record.

If exist then from TABLE 1 column called "identifier" check record names/values in rows such as quantity, color, discount, price1, price2 and copy content column values to TABLE 2 columns (names related - finded in rows of TABLE 1 column identifier.)

To simplify...Check ID from TABLE 1. If ID is good use identifier value and copy CONTENT column value from TABLE 1 to related ID and column name in TABLE 2.

表 2

You can pivot the source EAV table in a subquery using conditional aggregation, then join it with the target table for update. coalesce() can be used to handle missig attributes in the source table.

update table2 t2
inner join (
    select 
        post_id,
        max(case when identifier = 'quantity' then content end) quantity,
        max(case when identifier = 'color' then content end) color,
        max(case when identifier = 'discount' then content end) discount,
        max(case when identifier = 'price1' then content end) price1,
        max(case when identifier = 'price2' then content end) price2
    from table1 
    group by post_id
) t1 on t1.post_id = t2.id
set 
    t2.quantity = coalesce(t1.quantity, t2.quantity),
    t2.color    = coalesce(t1.color,    t2.color)
    t2.discount = coalesce(t1.discount, t2.discount)
    t2.price1   = coalesce(t1.price1,   t2.price1)
    t2.price2   = coalesce(t1.price2,   t2.price2)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM