【问题标题】:mysql Update table after querying from itmysql 从它查询后更新表
【发布时间】:2015-12-20 22:47:39
【问题描述】:

我有一张表格,里面有名字和姓氏。我还有另外两列要更新。这两列包含具有相同名字和相同姓氏的人数。例如,

first   last   samef   samel

John    Smith   1      2  
John    Adams   1      1  
Mary    Kate    0      0  
Kate    Adams   2      1  
Kate    Smith   2      2   
Kate    Smith   2      2  
Alice   Mirth   0      0

到目前为止,我只能提出这两个查询,但它们当然是不正确的。当我需要总计数时,它们会返回每个名称的总计数 - 1。另外,结果显示在单独的表格中。 我想知道是否应该使用存储过程,在其中使用变量来存储samef 和samel 的计数。然后将其插入到名称表中,但我不知道正确的语法。

SELECT first, last,
   ( SELECT COUNT(*) FROM names WHERE first = table1.first) AS samef 
FROM names AS table1

SELECT first, last,
   ( SELECT COUNT(*) FROM names WHERE last = table2.last) AS samel 
FROM names AS table2

我是 mySQL 的新手,所以请提供解释。

【问题讨论】:

  • 为什么要存储这些信息?
  • 这是教科书上的一个练习,其中有一节是关于从表格中读取时无法进行更新的部分。
  • 嗯,实际上,您通常不会存储可以从其他数据派生的数据。

标签: mysql sql-update


【解决方案1】:

就像草莓提到的那样,不要存储可以导出的信息。数据库擅长以最佳方式存储数据。 SQL 擅长提取表和派生/计算的数据。试试这个:

select `first`, `last`,
  (select count(*)-1 from test where `first` = t.`first`) as samef,
  (select count(*)-1 from test where `last` = t.`last`) as samef
from test t;

示例:http://sqlfiddle.com/#!9/9c673f/1

结果:

| first |  last | samef | samef |
|-------|-------|-------|-------|
|  john | smith |     1 |     2 |
|  john | adams |     1 |     1 |
|  mary |  kate |     0 |     0 |
|  kate | adams |     2 |     1 |
|  kate | smith |     2 |     2 |
|  kate | smith |     2 |     2 |
| alice | mirth |     0 |     0 |

【讨论】:

    猜你喜欢
    • 2015-09-02
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 2010-11-26
    • 2015-03-01
    • 1970-01-01
    • 2018-12-10
    相关资源
    最近更新 更多