SQLPro或PostgreSQL基于前一行值更新SQL行

时间:2017-12-25 20:18:40

标签: mysql sql postgresql

我无法使用我的SQL版本找到当前问题的答案,所以希望有人可以帮助我。

我使用MySQL和SQLPro作为客户端,或者我可以使用PostgreSQL pgAdmin 4。

方案我尝试使用之前的if(isset($_POST["register"])){ $username = trim($_POST['username']); $username = strip_tags($username); $username = htmlspecialchars($username); $password = trim($_POST['password']); $password = strip_tags($username); $password = htmlspecialchars($username); $email = trim($_POST['email']); $email = strip_tags($email); $email = htmlspecialchars($email); $conflictUserQuery = "SELECT username FROM members WHERE username='$username'"; $conflictUserResult = mysqli_query($conn, $conflictUserQuery); $conflictUserRow = mysqli_fetch_array($conflictUserResult, MYSQLI_ASSOC); $conflictMailQuery = "SELECT email FROM members WHERE email='$email'"; $conflictMailResult = mysqli_query($conn, $conflictMailQuery); $conflictMailRow = mysqli_fetch_array($conflictMailResult, MYSQLI_ASSOC); if(mysqli_num_rows($conflictUserResult) ==1){ $userConflictExists = TRUE; } elseif(mysqli_num_rows($conflictMailResult) ==1){ $mailConflictExists = TRUE; } else{ $hash = password_hash($password, PASSWORD_DEFAULT); $registerQuery = mysqli_query($conn, "INSERT INTO members (username, password, email) VALUES ('$username', '$hash', '$email')"); if($registerQuery){ $_SESSION['username']= $username; header("Location: index.php"); } } } 更新null值。

这是我的表:

not null value

enter image description here

如何使用primary_id name address id 1 bob 123 main 100 2 jane 123 main NULL 3 mike 217 2nd 200 4 jeff 217 2nd NULL 填充null值,以便not null values分组在我的列中保持不变?

感谢!!!

2 个答案:

答案 0 :(得分:0)

如果您想更新表格,这将在Postgres中使用:

update t
    set id = (select t2.id
              from t t2
              where t2.address = t.address and t2.id is not null
              fetch first 1 row only
             )
    where id is null;

在MySQL中,这将起作用:

update t join
       (select address, max(id) as max_id
        from t
        group by address
       ) tt
       on t.address = tt.address
    set t.id = tt.max_id
    where t.id is null;

答案 1 :(得分:0)

您可以尝试自行更新表格。我将您的表插入到我在postgres中创建的用户表中:

{{1}}

所以我的想法是我抓住所有非空地址和id组(假设地址总是与相同的id配对。我称之为_users。

将_users.address与原始users.address匹配。确保您只更新NULL users.id。