What is the proper way to automatically create new tables based on values in another table? For instance, If table A has a column named city that contains different city values then I would need to create a new table based on each different city. Then all records with the respective city needs to be inserted into it's respective table. Also, if the city contains a space in the name it needs to be replaced with a an underscore. How could the same be done in MySQL?
In MS ACCESS I could accomplish this by:
Using A Select And Replace Query Named SELREP
SELECT table_A.column1, table_A.column2, table_A.city, Replace([city]," ","_") AS table_name_column FROM table_A;
Create a Public Function MakeTableCity
Public Function MakeTableCity()
DoCmd.SetWarnings False
Dim db As Database
Set db = Application.CurrentDb
Dim distinctValues As DAO.Recordset
Set distinctValues = db.OpenRecordset("SELECT table_name_column FROM SELREP GROUP BY table_name_column", dbOpenSnapshot)
Do Until distinctValues.EOF
DoCmd.RunSQL "SELECT * INTO " & distinctValues("table_name_column") & " FROM SELREP WHERE table_name_column ='" & distinctValues("table_name_column") & "'"
distinctValues.MoveNext
Loop
DoCmd.SetWarnings True
Set distinctValues = Nothing
Set db = Nothing
End Function
If you are planning to create a new
table city with data about cities,
meaning one row for every city, then
go ahead and read the answer.
If , on the other hand, you are
planning to make a new table for
every city, with identical columns,
then your plan is very bad design.
Read about normalization first.
First alternative is to create a table named city with fields that you want. Example:
CREATE TABLE city
( id INT auto_increment PRIMARY KEY
, name VARCHAR(50) NOT NULL
, population INT
, state CHAR(2)
) ;
Then copy the different city names into it with:
INSERT INTO city (name)
( SELECT DINSTINCT city --- change "city" into REPLACE(city, ' ', '_')
FROM table_A --- for the small changes you want
) ;
Then, update the other fields (population, state, etc).
If no two cities have same name, the JOINs between the two tables can then be done using ON table_A.city = city.name
If not, (and better anyway as the Primary Key of city will be smaller), you may ALTER the structure of table table_A by adding a field cityid and dropping the city field. Then the JOINs between the two tables will be done using ON table_A.cityid = city.id
Second option is to directly create table city with:
CREATE TABLE city AS
( SELECT DINSTINCT city AS name --- change "city" into REPLACE(city, ' ', '_')
FROM table_A --- for the small changes you want
) ;
and then alter the table defining Primary Key, adding (population, state, etc).
Related
I need to port some data from tables on a development database into identical tables on the production database, but the production already has records with primary keys that match the dev database so I can't dump the data in with primary keysbundleRenderer.renderToStream
In this case, item_id is the primary key in the parent record, which is used to relate child records to it. Doing the insert of parent records will create a new primary key, so I need child inserts to also have the newly created primary key so that the relationship is maintained on the production databasebundleRenderer.renderToStream
my script so far:
<?php
$DB2connPROD = odbc_connect("schema","user", "pass");
$DB2connDEV = odbc_connect("schema","user", "pass");
//Get itemt records from dev
$getDevitems = "
select item_id,item_typet_id,item_identifier,expiration_timestamp
from development.itemt where item_typet_id in (2,3)
";
//$getDevitems will get records that have a primary key item_id which is used to get the records in the following select queries
foreach($getDevitems as $items){
//Get all comments
$getComments = "
select tc.item_id, tc.comment, tc.comment_type_id from development.item_commentt tc
inner join development.itemt t on tc.item_id = t.item_id
where t.item_id = {item_id_from_getDevitems}
";
$insertitem = "INSERT into production (item_identifier,expiration_timestamp)
values (item_identifier,expiration_timestamp)";
$insertComment = "INSERT into productionComment (item_id, comment, comment_type_id)
values (item_id, comment, comment_type_id)";
}
?>
So if $getDevitems returns
item_id | item_typet_id | item_identifier | expiration_timestamp
----------------------------------------------------------------------------
123 1 544 '2020-03-01 12:00:00'
I would want it to now run the comment select with 123 as the ID in the where clause:
select tc.item_id, tc.comment, tc.comment_type_id from development.item_commentt tc
inner join development.itemt t on tc.item_id = t.item_id
where t.item_id = 123
Now for my legacy parent record I have all of the parent data and all of the relational child data. so I want to insert the new parent record into the database, creating the new ID, and inserting the child record with the newly created primary key/ID. So for the new parent record I would do:
$insertitem = "INSERT into production (item_identifier,expiration_timestamp)
values (544,'2020-03-01 12:00:00')";
Let's say that creates the new record with item_id = 43409. I want my comment insert to be:
$insertComment = "INSERT into productionComment (item_id, comment, comment_type_id)
values (43409, comment, comment_type_id)";
Bottom LIne: I need to take relational data (all based on item_id) from a development database, and insert these into a new database which creates a new primary key but I need to keep the relationship.
How can I properly finish this to do what I need and make sure I maintain the full relationship for each originally selected item?
Given that your inserts are:
$insertitem = "INSERT into production (item_identifier,expiration_timestamp)
values (item_identifier,expiration_timestamp)";
$insertComment = "INSERT into productionComment (item_id, comment, comment_type_id)
values (item_id, comment, comment_type_id)";
It looks like you are using an identity column for item_id. You can retrieve the most recent generated identity value using the IDENTITY_VAL_LOCAL() function so the second insert should be:
$insertComment = "INSERT into productionComment (item_id, comment, comment_type_id)
values (IDENTITY_VAL_LOCAL(), comment, comment_type_id)";
I cannot help with PHP but with DB2 for IBMi you have different solutions :
If i understand it correctly item_id is a GENERATED ALWAYS as IDENTITY column
You can get newly created item_id using
select item_id from final table (
INSERT into production (item_identifier,expiration_timestamp)
values (544,'2020-03-01 12:00:00')
)
Or you can force value of item_id with dev value or your own increment
INSERT into production (idtem_id, item_identifier,expiration_timestamp)
values (<your value>, 544,'2020-03-01 12:00:00')
OVERRIDING SYSTEM VALUE
In this case you will have to set next value for item_id by issueing
alter table production alter column item_id restart with <restart value>
I'm using Laravel 5.1 , I've a model Customer which has many Vehicles.
I set validations for Vehicle model like this :
public static $Rules = array(
'code' => 'required|unique:vehicles',
'registernumber' => 'required|unique:vehicles'
);
Till now, all is fine : I can't insert two vehicles with the same code or registernumber.
What I want to do is :
Can I set a custom validation which allows me to insert unique code or registernumber value just for a given CustumerID ?
Example :
Customer1 :
Vehicle1: code1, registernumber1
Vehicle2: code2, registernumber2
(Here I can't insert for example two codes having 'code1' value with Customer1)
Customer2 :
Vehicle1: code1, registernumber1
Vehicle2: code5, registernumber5
(Here I can't insert for example two registernumbers having 'registernumber5' value with Customer2)
Any idea please ?
As long as the customer id is in that table. The way the unique validation rule works is as follows:
unique:
[table name, optionally with a connection name],
[the column you are checking for uniqueness, optional],
[the id of the row that will be ignored in the check (for example if you are updating a row, you want the row you are updating to not be included), optional],
[the column name that contains the id you are running the check against, optional],
[additional where clauses (where_column, where_value)]
So, if your table schema looks like this:
vehicle_id, code_number, registration_number, customer_id
And you only want to run the unique check for rows of the same customer, you can do this:
$customer_id = 'whatever';
$Rules = array(
'code' => 'required|unique:vehicles,code_number,NULL,vehicle_id,customer_id,'.$customer_id
);
That will run the check only on rows where('customer_id', $customer_id)
Syntax
ALTER TABLE `tablename`
ADD UNIQUE KEY `my_unique_key` (`colname1`, `colname2`);
In your example
ALTER TABLE `yourtable`
ADD UNIQUE KEY `unique_reg` (`customername`, `vehicle`, `code`, `regno`);
Try this but you should handle the db_error otherwise it affects the user experience
I am inserting data into a database fine with the user entering a reference number eg 1234. Can I change my insert to not require the user to input the value and for the last value entered to be checked and then the reference number being inserted be incremented by one and then inserted with the other data. Bit of a new bee. Here is my current code
$Reference_No = $_POST['Reference_No'];
$Property_Name = $_POST['Property_Name'];
$Property_Area = $_POST['Property_Area'];
mysql_query("INSERT INTO properties (Reference_No, Property_Name, Property_Area)
VALUES ('$Reference_No', '$Property_Name', '$Property_Area')");
You need to make the Reference_No an AUTO_INCREMENT.
Step 1:Create table
CREATE TABLE properties (
Reference_No int AUTO_INCREMENT ,
Property_Name varchar(255),
Property_Area varchar(255),
PRIMARY_KEY (Reference_No)
)
Step 2 : Set the start for auto increment of primary key if you like
ALTER TABLE properties AUTO_INCREMENT=1234;
Step 3: Insert the data into the table
INSERT INTO properties (Property_Name, Property_Area)
VALUES ('$Property_Name', '$Property_Area')");
interogate the database for the Reference NO (where property name matches if you need it)
$reference_no_query = mysql_query("SELECT Reference_No FROM properties WHERE Property_Name = $Property_Name");
pull the Reference No out of the database
$Reference_no = mysql_fetch_array($reference_no_query)
display the Reference no
echo $Reference_no('Reference_no');
you can (and should) tie the data to a variable then echo the var like this:
$Reference_no_display = $Reference_no('Reference_no');
then display it directly from the variable anywere and as many times as you want in the page below the query:
echo $Reference_no_display;
This seems to do the trick for the final bit
printf("Last inserted record has id %d\n", mysql_insert_id());
I am using Php to insert values into MySQL table.
What i am trying to do is:
There are three columns that i have to check. 'namel1', 'namel2' and 'namel3'.
Conditions:
If '$name' does't exist in any of the three column then put value in 'namel1'.
If '$name' exist in 'namel1' then put value in 'namel2' and if 'namel2' contains the value then put it in 'namel3'.
My current MySQL query to insert name and image path is this i want to modify it to meet above conditions:
$chk_img_db = mysql_query("select * from cvapptable where img_path='$cvh_myimg_url'");
if(mysql_num_rows($chk_img_db)<1) {
mysql_query("insert into cvapptable(namel1,img_path) values ('$name','$cvh_myimg_url')");
}
I unable to get any solution from web.
Please help. Thank you.
It's not easy to find on the net because it's a situation you shouldn't get yourself into.
You should consider normalizing the table.
Instead of having a table with the columns:
cvapp: id | img_path | namel1 | namel2 | namel3
Consider changing it to two tables:
cvapp: id | img_path
names: id | cvapp_id | name
To then select every name, you just do a query like so:
SELECT name
FROM cvapp INNER JOIN names on cvapp.id = names.cvapp_id
WHERE <condition>
That way, you can have as many names as you want, and it's much easier to insert a new one:
INSERT INTO names (cvapp_id, name) VALUES (56, "Name 1");
INSERT INTO names (cvapp_id, name) VALUES (56, "Name 2");
INSERT INTO names (cvapp_id, name) VALUES (56, "Name 3");
you can try self join and search column of you tables
How can I uniquely identify two or more columns, that I have used table named address in the database, now address is has fields like street name, suite name and street num.
strnum | strnam | sutname
1 | xyz | 32
1 | xyz | 32
now how can I uniquely these three columns. That is I want to check whether these three column are already inserted or not. If any field valus is changed than its ok, it will insert new one. but in case all three similar field..Help me to combinely identify these three fields.
You do it by adding unique constraint.
ALTER TABLE your_table ADD UNIQUE(strnum, strnam, sutname);
Then you do the following:
INSERT IGNORE INTO your_table (strnum, strnam, sutname) VALUES ('1', 'xyz', 'etc');
If the value exists already - no insert will happen and no errors will be raised (that's what the IGNORE part is).
By the way why do you use such short and vague column names? It's not the DOS era any more, you can be descriptive with your column names.
$query = "SELECT * FROM `address` WHERE `strnum` = '$strnum' AND `strnam` = '$strnam' AND `sutname` = '$sutname' LIMIT 1";
$result = mysql_query($query);
if (!mysql_num_rows($result)) {
// If you get to here, there is no existing record
$query = "INSERT INTO `address` (`strnum`,`strnam`,`sutname`) VALUES ('$strnum','$strnam','$sutname')";
if (!mysql_query($query)) print('Insert failed!');
} else print('Record already exists!');
EDIT I just added a missing ; so this parses...
just add them as unique keys in table structure and you'll not be able to insert two of them
you can do something like this
SELECT * FROM table WHERE col1 = $something AND col2 = $something2 AND col3 = $something3
(remember about escpaing php variables)
if the record is returned it means it exists. You can also add LIMIT 1 to make it faster.
if your question is about ENSURING that no duplicates occur in the table (for those 3 columns), then probably the best solution is to add UNIQUE index on those three columns.