【问题标题】:Advanced MySQL Insert with multiple tables [closed]具有多个表的高级 MySQL 插入 [关闭]
【发布时间】:2014-03-23 23:21:38
【问题描述】:

我正在尝试使用联合表和现有值填充 MySQL 中的一列。

我有两张桌子 -

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

我想在每一行的 citations.refPaperID 列中填入具有匹配 citations.title LIKE pages.title + citations.year = pages.year 的论文行的 paper.paperid。

【问题讨论】:

  • 您是要在引文表中插入新行还是确实要更新其中的当前行?
  • 更新引文表中的当前行因此对于引文表中的每一行,rePaperID 值指向与引文中具有相同标题和年份的论文的 paperid

标签: mysql database insert sql-insert


【解决方案1】:

试试这个:

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

但要使其工作,SELECT 查询必须匹配并返回一条记录,这意味着您的引文表中的记录必须具有唯一的标题+年份组合。

编辑

MySQL 没有FIRST()LAST() 的实现,所以要获得第一个匹配,您可以像这样使用LIMIT 1

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

【讨论】:

  • 如果子查询找到多个匹配项,有什么办法让它使用第一条记录?
  • 并且仅在 citations.year 和 citations.year 不为 NULL 时更新该行
  • @BradStevenson 是的,您可以使用LIMIT 1。我会更新我的答案。
【解决方案2】:

我倾向于使用join

update citations c join
       papers p
       on c.title = p.title and
          c.year = p.year     
    set c.refPaperID = p.paperid;

【讨论】:

    猜你喜欢
    • 2013-11-11
    • 2011-03-14
    • 2013-12-01
    • 1970-01-01
    • 2014-09-22
    • 2022-06-22
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多