2

I have an insert query with two subqueries:

INSERT INTO Work_Order (ID ,BRANCHID,BRANDID)   
VALUES (66),
SELECT ID FROM Brands WHERE NAME = 'branch'
SELECT ID FROM Branches WHERE NAME = 'brand'

I know it's not a correct syntax but I need the correct one, the ID must be 66 and BRANCHID,BRANDID are foreign keys for another tables

3
  • if you are inserting something into a database by fetching that something from another table, then your design is wrong. I say rethink. Commented Jul 22, 2012 at 19:40
  • look I am not a DB professional , the design consists of 3 tables the first is the one that I am inserting to, BRANCHID is a foreign key for another table called branches and the same for brands , the user writes the name of the branch and I will insert its ID , I think it's a good design, isn't it?? Commented Jul 22, 2012 at 21:55
  • oh stupid of me, thats fine, I for a moment thought you were inserting 'branch', 'brand' etc and not their ids. Apologies.. :) Commented Jul 23, 2012 at 6:36

3 Answers 3

4

66 is a literal, use it and two subselects in your SELECT:

INSERT INTO Work_Order (ID ,BRANCHID,BRANDID) 
SELECT
  66 AS ID,
  (SELECT ID FROM Brands WHERE NAME='branch') AS BRANCHID,
  (SELECT ID FROM Brands WHERE NAME='brand') AS BRANDID

MySQL is lenient about the existence of a FROM clause, so this ought to work. Many other RDBMS would require you to put in a FROM clause with some table even though it isn't used in the SELECT (like Oracle's Dual table).

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

Comments

1

This is how it worked perfectly with me

INSERT INTO Work_Order (NUMBER,BRANDID,BRANCHID)    
SELECT 66,B.ID,Br.ID
FROM Brands as B,Branches as Br
WHERE B.NAME = 'brand' AND Br.NAME = 'branch'

Comments

0

If your subqueries return more than one row, you have to decide how to combine the values. The following query assumes you want all combinations:

INSERT INTO Work_Order (ID ,BRANCHID, BRANDID)
    select 66, branches.id, brands.id
    from brands cross join branches
    where branches.NAME = 'branch' and
          brands.NAME = 'brand'

(I changed the where clause to look for the name within the same table as the name . . . branches.Name = 'branch' rather than branches.name = 'brand'.)

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.