shanetastic Posted September 30, 2011 Share Posted September 30, 2011 Here is my query: INSERT INTO Territories (RepId, PrincipalID, StateID) SELECT Reps.RepID Where Reps.RepName = 'ARepName' SELECT Principals.PrincipalID Where Principals.PrincipalName = 'APrincipalName' SELECT States.StateID Where States.StateAbbreviation = 'LA' I have four tables: Reps ------ RepID RepName Principals ----------- PrincipalID PrincipalName States -------- StateID StateAbbreviation Territories ------------ RepID PrincipalID StateID I know the RepName, PrincipalName, and StateAbbreviation. I am trying to use those to pull the respective IDs from the respective tables and then insert a row into Territories. What am I doing wrong? Quote Link to comment https://forums.phpfreaks.com/topic/248190-need-help-with-insertselectwhere/ Share on other sites More sharing options...
fenway Posted September 30, 2011 Share Posted September 30, 2011 You need to JOIN those other tables first. Quote Link to comment https://forums.phpfreaks.com/topic/248190-need-help-with-insertselectwhere/#findComment-1274504 Share on other sites More sharing options...
shanetastic Posted September 30, 2011 Author Share Posted September 30, 2011 Am I getting warmer? INSERT INTO Territories (RepId, PrincipalID, StateID) JOIN StatesON Territories.StateID = States.StateID JOIN Reps ON Territories.RepID = Reps.RepID JOIN Principals ON Territories.PrincipalID = Principals.PrincipalID SELECT Reps.RepID as RepID Where Reps.RepName = 'ARepName' SELECT Principals.PrincipalID as PrincipalID Where Principals.PrincipalName = 'APrincipalName' SELECT States.StateID as StateID Where States.StateAbbreviation LIKE '%LA%' Quote Link to comment https://forums.phpfreaks.com/topic/248190-need-help-with-insertselectwhere/#findComment-1274509 Share on other sites More sharing options...
awjudd Posted October 1, 2011 Share Posted October 1, 2011 You are inserting into a mapping table so chances are you may not have that data in the application as of yet. INSERT INTO Territories ( RepID, PrincipalID, StateID ) SELECT ( SELECT RepID FROM Reps WHERE RepName = 'ARepName' ) AS RepID , ( SELECT PrincipalID FROM Principals WHERE PrincipalName = 'APrincipalName' ) AS PrincipalID , ( SELECT StateID FROM States WHERE StateAbbreviation LIKE '%LA%' ) AS StateID Assuming they all return 1 row. If they don't then you will need a bit more for the query to get it to work. ~juddster Quote Link to comment https://forums.phpfreaks.com/topic/248190-need-help-with-insertselectwhere/#findComment-1274690 Share on other sites More sharing options...
shanetastic Posted October 1, 2011 Author Share Posted October 1, 2011 Worked perfectly, thanks! Quote Link to comment https://forums.phpfreaks.com/topic/248190-need-help-with-insertselectwhere/#findComment-1274728 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.