Domanda

I am trying to fill a column in MySQL using a joint table and existing value.

I have two tables -

__________________________
|          papers        |   
| paperid | title | year |   
| 1.0.2   | Awed  | 1999 |   
_______________________________________
|           citations                 |
| title | year | paperid | refPaperID |
| othP  | 1999 | 1.3.4.5 | NULL       |

I want to fill the citations.refPaperID column in every row with the paper.paperid of the row in papers which has a matching citations.title LIKE papers.title + citations.year = papers.year.

È stato utile?

Soluzione

Try this:

UPDATE citations SET
citations.refPaperID = (SELECT papers.paperid
                        FROM papers
                        WHERE citations.title = papers.title
                        AND citations.year = papers.year)

But for this to work, the SELECT query must match and return one single record, which means that the records in your citations table must have unique title+year combination.

Edit

MySQL does not have an implementation of FIRST() and LAST(), so to get the first match, you can use LIMIT 1 like this:

UPDATE citations SET
citations.refPaperID = (SELECT papers.paperid
                        FROM papers
                        WHERE citations.title = papers.title
                        AND citations.year = papers.year
                        LIMIT 1)

Altri suggerimenti

I would be inclined to do this with a join:

update citations c join
       papers p
       on c.title = p.title and
          c.year = p.year     
    set c.refPaperID = p.paperid;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top