0

I have been trying different sql queries that do the following:

For all the table entries which have a field that has a field_value in clumn_a of table_1 which equals any field value in column_b of table_2 insert the id of the field in table_2 in id_of_the_other_entry_column of table_1.

However I can only use SQL and not use anything else than a SQL command for that. Is this even possible without the help of another programming language? If so.. any tips?

EDIT: An example:

TableOwner  
id  name
1   SomeCompany
2   SomeOtherCompany

TableContracts
Name               ownerid
NewCompany       Null --> Should remain null after the query
SomeCompany     Null -->Should change to 1 after the query
SomeCompany        Null -->Should change to 1 after the query
SomeOtherCompany   Null -->Should change to 2 after the query

thanks

2 Answers 2

1
update tableContracts t2 set t2.ownerid=t1.id where exists( select t1.id from tableowner t1 where t1.name=t2.Name)
Sign up to request clarification or add additional context in comments.

1 Comment

I can't see how this can work: the scope of correlation name t1 is limited the subquery yet it is being used outside of the subquery.
1
UPDATE
    table_2
SET
    id_of_the_other_entry_column = t1.ID
FROM
    table_2 t2
INNER JOIN
    table_1 t1
ON 
    t1.column_a = t2.column_b

EDIT:

Just tried this with MySQL, without success. With MySQL use:

UPDATE
    table_2 as t2
SET
    id_of_the_other_entry_column = (SELECT
                                        t1.ID
                                    FROM
                                        table_1 as t1
                                    WHERE
                                        t1.col_a = t2.col_b
                                    )

Importent: If table_1 contains more then one row with table_1.col_a equal to table_2.col_b the command will abort.

6 Comments

But the select will return a set of many different ids since t1.col_a = t2.col_b is true for many different ids.
Hint: If you want to make even more complex operations you don't need to use other languages. You also can create Stored procedure in many sql db's. MySQL: dev.mysql.com/doc/refman/5.0/en/create-procedure.html
@marco: to solve problem with multiple return rows just add LIMIT 1 (MySQL) or AND rownum = 1 (Oracle) to the end of subquery
@Alexander Malakhov: in this case he doesn't get the a reference from table_2 to all table_1 rows. @marco: with one-to-many relation, the relation id must set to table_1, not to table_2
@Wowa: as I understood question, it OK
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.