0

I have got two tables.

assets table

   |  AID  | NAME | 
   | 1234  | item1|

item table

   |  BID  | ITEM | 
   |       |      |

Question: How do I insert a data into item table only when the same data I want to insert is present in assets table? or is it even possible? Say I can only insert into item table BID value(1234) only when assets table AID value(1234) is present. I tried doing this:

INSERT INTO 'item'('BID') VALUES (1234) WHERE 'item'.BID='assets'.AID
1
  • What should be inserted as ITEM value then? 'item1' string? Also, do you want this 'WHERE' check applied for a single operation only, or you want to copy that assets table as whole? Commented Oct 16, 2012 at 23:14

3 Answers 3

1
INSERT INTO item (BID) SELECT assets.aid FROM assets WHERE aid = 1234;

Use DISTINCT in the SELECT if you may find multiple matches and don't want more than one row inserted.

Also, use a foreign key constraint if you want to just restrict the insert in the database. Once you have that, you don't need to conditionally insert. Just insert and let the database fail the attempt if the aid is not already present in the parent table.

Sign up to request clarification or add additional context in comments.

Comments

0

You can't use WHERE with the INSERT statement as mysql doesn't support it. Just remove the WHERE part and it should work.

But you'll have to check separately whether the data exist in the other table (or within a sub-query).

1 Comment

But what i want is that only when the value AID(primary key) is present in the assets table then only I can insert the same data into item table. I have no idea how to go about checking using two tables
0

You could use dynamic SQL and execute it later, but that's ugly. Just do an IF conditional. If the record exists in Value, run an insert, else, do not.

Try something like this:

(SELECT Count(*) FROM Value WHERE BID = '1234') > 0
    --your insert--

Comments

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.