I have 2 tables with the same columns.
for example
table 1
id
name
height
weight
table 2
id
name
height
weight
The data is table 2 is complete. But in table 1, only some data exists, and the rest of the columns are empty. for example:
table 1 table 2
id 4 4
name (empty) salman
height 5'11" 5'9"
weight (empyy) 65kg
I want a single script, that will allow me to update the table 2 with values from table 1, but only where it exists. In places where the table 1 is empty, I want to retain the data that already exists in table 2.
I've tried various ways, but all required multiple queries and are long and hectic. I want to know if there is a simpler way to get this done? Preferably in a single query?
Thank you
You can try by joining the 2 tables and then using the CASE keyword to conditionally update the fields:
UPDATE table2 t2 INNER JOIN table1 t1 USING (id)
SET
t2.name = CASE WHEN (t1.name IS NULL) THEN t2.name ELSE t1.name END
t2.height= CASE WHEN (t1.height IS NULL) THEN t2.height ELSE t1.height END
t2.weight = CASE WHEN (t1.weight IS NULL) THEN t2.weight ELSE t1.weight END
http://dev.mysql.com/doc/refman/5.5/en/case-statement.html
http://dev.mysql.com/doc/refman/5.5/en/update.html
Related
I have 3 database and I want to fetch data from 2 db and insert into another 1 but I have some problems doing it.
Database1 'first' : Table 'items':
id
name
price
1
Crystal
30
2
Ruby
20
Database 2 'second' : Table 'Shop':
id
name
items_id
state
1
KK shop
1
NY
2
ABC Supermarket
2
AL
I need to fetch data from table Items and search then 'name' in table Shop by using the 'id' from table Items.
Then I want to insert the data into table Details.
This is how it show look like, from empty to this:
Database 3 'third' : Table 'Details':
id
items.id
items.name
shop.name
1
1
Crystal
KK shop
2
2
Ruby
ABC Supermarket
My questions :
1)Since I have 3 database how should I connect to all of them in the same time? Should I create 3 php file to connect each of them and then include 3 of them in the same file?
2)If I want to copy all columns from a table to another table can I do like this? Will this copy all columns from 'first.items' to 'third.details'?
SELECT * from first.items
INSERT INTO third.details;
3)My SQL query,
SELECT * FROM first.items,
SELECT name FROM second.shop
WHERE first.items.id = 1,
INSERT INTO third.details (id,items.id,items.name,shop.name)
VALUES (1,first.items.id,first.items.name,second.shop.name);
After executing the query my table Details is unable to get any data, what is the problem? Thanks.
When you need to insert into some table data selected from other tables you can use next approach:
first: build query that select data that should be inserted. In your case in can be next:
SELECT 1, items.id, items.name, shop.name
FROM first.items
JOIN second.shop ON shop.id = items.id
WHERE items.id = 1;
second: combine the query with INSERT statement like:
INSERT INTO third.details (id, items_id, items_name, shop_name)
SELECT 1, items.id, items.name, shop.name
FROM first.items
JOIN second.shop ON shop.id = items.id
WHERE items.id = 1;
rename column : Database 2 'second' : Table 'Shop':
items.id to item_id
Database 3 'third' : Table 'Details':Set id as auto increment
Use join to combine first two tables:
SELECT items.id,items.name,shop.name FROM shop as shop left join items as items on items.id = shop.item_id WHERE items.id = 1,
INSERT INTO third.details (items.id,items.name,shop.name)
VALUES (first.items.id,first.items.name,second.shop.name);
Your INSERT INTO SELECT syntax is misplaced
In order to insert the entire table to the other one, the two must share compatible columns. Both counts and types.
The tables seem a bit unorganised but if you'd like to go through with it, the correct query should be as followed
INSERT INTO `third`.`Details` (`items.id`, `items.name`, `shop.name`)
SELECT `second`.`Shop`.items_id, `first`.`items`.name, `second`.`Shop`.name
FROM `first`.`items`, `second`.`Shop`
WHERE `second`.`Shop`.id = 1 and `first`.`item`.id = 1;
Also changing the where clause to
`second`.`Shop`.id = `first`.`items`.id;
should allow you to insert all the entries to your target table at once
We have two tables with same structure (MSSQL)
We want to compare
(ID) 122 from table1
with
highest ID 122 from table2
If there is one or more differences, we want to show the name of the column along with the data it holds from both tables.
I do not want to list all the columns out, as there is over 150
Something like (psuedo): -
Select * from table1
Select * from table2
Compare table1 (column by column) with table2 (column by column)
Show changes : -
'Name' WAS 'John' NOW 'James' CHANGED 3/11/2016 3.45pm
'Mobilenum" WAS '02373643743' NOW '0983783738' CHANGED 4/11/2016 12.46pm
Do not want to try triggers...need php code....
We should not need to give any column names as it should run though them all dynamically...
Why do you not want to list the columns - Is this table going to change regularly?
You can still create the SQL dynamically - but store it as a static string.
Lots of examples for this (hint use information_schema.columns)
If the tables are not huge then I would p[rob write a bunch of Tests (1-per column) and UNION All them together - Then only return the Data where diff = true
Eg
Select * from
(
Select case when ISNULL(table1.columnA, -999) <> ISNULL(table2.columnA, -999) then 1 else 0 end as diff, table1.columna as Old_Val, table2.columnA as new_val
from table1 join table2 on ...
UNION ALL
/* etc etc * 150 ... */
) as x
where x.diff = 1
I have two tables in a mysql database.
I need to select columns just from the first table and do the condition in the 2 table for example :
I have in the first table the columns:
amount | date | name | address
and in the second I have:
amount | date | cin | time
The condition would be WHERE amount = amount and date = date.
But select just the data from the first table. I dont need to display the data of the second table.
You could use the EXISTS operator to find out whether a corresponding row in the second table exists:
SELECT * FROM first_table t1
WHERE EXISTS (
SELECT 1
FROM second_table t2
WHERE
t1.amount = t2.amount AND t1.date = t2.date
);
This ensures you won't have to use DISTINCT to reduce your resultset, if more than one row with your condition exists in the second table.
Hello i have two tables with a PK---->FK Relationship in InnoDB Engine---->MySQL&PHP
The Relationship is one---->many between first table which is 'Properties' and second
table which is 'propertyimages'. every row in first table is unique but in second table
every row of first table has got many rows in second table How can i **SELECT unique row from
first table and all info about first table from second table here is my query:
SELECT DISTINCT properties.PropertyName,
properties.PropertyStatus,
propertyimages.PropertyImageID,
propertyimages.ImagePath
FROM properties
INNER JOIN propertyimages
ON properties.PropertyImageID=propertyimages.PropertyImageID
AND propertyimages.PropertyImageID=8;
it gives result:
PropertyName PropertyStatus Propertyid property Image Path
Appartment For Lease 8 upload/hydrangeas.jpg
Appartment For Lease 8 upload/jelsh.jpg
Appartment For Lease 8 upload/penguins.jpg
Appartment For Lease 8 upload/tulips.jpg
In this result the PropertyName and PropertyStatus is Repeated but i want a
unique as its stored in the first tableThe propertyName and PropertyStatus
belongs to first table.The Propertyid and PropertyImagepath belings to second table.
unfortunately a join will create a record for each element found in table 2 with a matching parent element (id 8) in the first table.
you could use a GROUP BY id 8 on the first table field, but you may not get all the results you want since it will take the first image only.
could you restructure your process so that when it comes to the images (and thier display) you could just run a single query to get every image related to property 8
you could always use a nested query (presuming you're looking to display images on a page for a property, etc)
$query1 = mysql_query("SELECT Propertyid, PropertyName, PropertyStatus FROM properties WHERE (search criteria)");
if (mysql_num_rows($query1) > 0) {
while ($q1Row = mysql_fetch_array($query1)) {
// Insert property specific data here before you display the images
echo $q1Row['PropertyName']."<br>\n";
echo $q1Row['PropertyStatus']."<br>\n";
$query2 = "SELECT PropertyImageID, ImagePath FROM propertyimages WHERE PropertyImageID='".$q1Row['Propertyid']."'"
if (mysql_num_rows($query2) > 0) {
while ($q2Row = mysql_fetch_array($query2)) {
// add code here to do whatever you want with the images
echo '<image src="'.$q2Row['ImagePath'].'"><br>\n';
}
}
}
}
}
it would also help to know your DB structure .. i'd imagine you'd want something like this
table 1 (properties)
PropertyID (Primary Key)
PropertyName
PropertyStatus
table 2 (propertyImages)
ImageID (Primary Key)
PropertyID (many to one reference to PropertyID in table 1)
ImagePath
I may be a bit oblivious to the FK method so if there is a lesson here for me as well, i'd love to hear what input you have.
you are one step away from the solution, you just need to select from second table and then for first so you will have all you result matched
SELECT DISTINCT properties.PropertyName,
properties.PropertyStatus,
propertyimages.PropertyImageID,
propertyimages.ImagePath
FROM propertyimages
INNER JOIN properties
ON propertyimages.PropertyImageID = properties.PropertyImageID
AND propertyimages.PropertyImageID=8;
You could achieve this with GROUP_CONCAT. But I also think, it is better to make two queries. Nothing wrong with that.
SELECT DISTINCT properties.PropertyName,
properties.PropertyStatus,
propertyimages.PropertyImageID,
GROUP_CONCAT(propertyimages.ImagePath)
FROM properties
INNER JOIN propertyimages
ON properties.PropertyImageID=propertyimages.PropertyImageID
AND propertyimages.PropertyImageID=8;
GROUP BY propertyimages.PropertyImageID
What i want, to display rows from a table which is selected by a field from other table single value, lets say to display images from a table by last category id.
I have this type of query, but this return me all matching keys rows, if i inset LIMIT 1 then it return one row...
SELECT i.prof_image FROM profile_images i
JOIN images_cat cat ON (cat.cat_id = i.cat_id)
GROUP BY i.prof_image;
//OR LIMIT 1;
Any idea to fix this problem. (i.e. displaying the latest category images)?
This will work for your specific example.. If you need to be more selective, then please post some more details..
SELECT i.prof_image
FROM profile_images i
WHERE cat_id = (select max(cat_id) from images_cat)
SELECT * FROM table_1
LEFT JOIN table_2 ON table_1.id = table_2.id
This query will grab all things in table_2 that have the same id value.
Note that it is a LEFT JOIN - which means that if there are no matching values in table_2, it will still return the values from table_1.
What is your intent with using last()?
Hope this helps.