简体   繁体   English

在这种情况下如何编写SQL语句?

[英]How to write SQL statement in this case?

For some reason, I'd like to change the database. 由于某种原因,我想更改数据库。

It's not possible to change these values manually one by one as there are so much records. 由于记录太多,因此无法手动一一更改这些值。

Please advise how to write this SQL, thanks. 请告知如何编写此SQL,谢谢。

From: 从:

 id  percentage    type
  1     6        services
  1     10       testing
  3     8        services
  3     20       testing
  6     61       services
  6     90       testing

To: 至:

id percentage    type
1     10       services
1     10       testing
3     20       services
3     20       testing
6     90       services
6     90       testing

With a correlated query, you can do it like so: 使用相关查询,您可以这样进行:

SELECT 
  t1.id,
  (SELECT MAX(t2.percentage) 
   FROM table1 t2 
   WHERE t2.id = t1.id) percentage,
  type
FROM Table1 t1

SQL Fiddle Demo SQL小提琴演示

If you want to select only see Mahmoud Gamal's Answer 如果只想选择,请参见Mahmoud Gamal的答案

But if you want to permanently change the value, Use UPDATE 但是,如果要永久更改该值,请使用UPDATE

UPDATE  tableName a
        INNER JOIN
        (
            SELECT id, MAX(percentage) AS maxPercentage
            FROM tableName
            GROUP BY id
        ) b ON a.ID = b.ID
SET a.percentage = b.maxPercentage;

Write a reference table to match the scales between your services and testing values (see example below) and then write an update query based on each row of your reference table: 编写参考表以匹配服务和测试值之间的比例(请参见下面的示例),然后根据参考表的每一行编写一个更新查询:

id  service_val  testing_val
1       6        10
2       8        20
3       61       90

Running a select all on this table and iterating through the results in something like php, python, etc. would allow you to dynamically replace the values in your mysql query. 在此表上运行全选并在诸如php,python等之类的结果中进行迭代,将允许您动态替换mysql查询中的值。 This approach allows for the two values to not have a direct correllation as opposed to other answers (ie: service doesn't have to be a percentage of testing) 这种方法允许两个值与其他答案没有直接相关性(即:服务不必一定是测试的百分比)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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