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
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
I have two tables first and second.
first Table:
ID NAME ADDRESS
1 test testing address
2 test1 testing address
3 test2 testing address
4 test3 testing address
second Table:
T_ID Partner_id date
1 2 12345678
3 4 32164584
If input T_id is given. Then corresponding Partner_id is taken and it is compared with the ID from first table and corresponding row should be selected.
Can you please tell me.
In php I can write this with two queries but I want it to be in a single query.
Queries in php:
$q=mysqli_query($conn, "SELECT Partner_id from second where T_ID=1");
$qa=mysqli_fetch_array($q);
$w=mysqli_query($conn, "SELECT * from first where ID=$qa[0]");
But, how to combine this two statements?
The specified result can be returned using a query with a join operation.
SELECT f.*
FROM first f
JOIN second s
ON s.Partner_id = f.ID
WHERE s.T_ID=1
Note that there is a potential for this to return more rows that the original, if the first query returns more than one row. (That is, we don't assume that T_ID is unique in second, or that every row with a given T_ID value will have identical values for Partner_id.)
There are other query patterns that will return an equivalent result, but the join operation is the normative pattern.
try to use union ,see this this link
where The SQL UNION operator combines the result of two or more SELECT statements.
SELECT * FROM first WHERE ID IN( SELECT Parent_id FROM second WHERE T_ID = 1 )
or
SELECT * FROM first WHERE ID = ( SELECT Parent_id FROM second WHERE T_ID = 1 )
SELECT * FORM first_table AS f
JOIN second_table AS s
ON s.parent_id =f.id
WHERE s.T_ID = $id
I want to make a notifications page which shows notifications about a variety of things, like new followers, new likes, new comments etc. I want to display a list that shows all of these things in chronological order.
My tables look like this:
COMMENT
1 comment__id
2 comment__user_id
3 comment__snap__id
4 comment__text
5 comment_add_time
LIKE
1 like__id
2 like__user__id
3 like__snap__id
4 like__like_time
FOLLOW
1 follow__id
2 follower__user__id
3 followed__user__id
4 follow__follow_time
5 follow__request_status
I would load the followers of a user with a query like this:
try {
$select_followers_query = '
SELECT follow.follower__user__id, follow.followed__user__id, follow.follow__request_status, user.user__id, user.user__username, user.user__profile_picture, user.privacy
FROM follow
JOIN user ON(follow.follower__user__id = user.user__id)
WHERE followed__user__id = :followed__user__id';
$prep_select_followers = $conn->prepare($select_followers_query);
$prep_select_followers->bindParam(':followed__user__id', $get_user__id, PDO::PARAM_INT);
$prep_select_followers->execute();
$followers_result = $prep_select_followers->fetchAll();
$followers_count = count($followers_result);
}
catch(PDOException $e) {
$conn = null;
echo $error;
}
Next, I get the results like this:
foreach($followers_result AS $followers_row) {
$follower_user_id = $followers_row['follower__user__id'];
// the rest of the variables will come here...
}
I will have separate SQL queries like the one above which each load something. The example above loads the followers, another query will load the comments etc. I want to display the results of all of these queries and display them in chronological order, like this:
#user_1 liked your photo
#user_4 started following you
#user_2 commented on your photo
etc...
How can I achieve this? SQL UNION requires the tables to have the same number of columns and the selected columns must have the same name. I don't have all that. Moreover, every kind of result (follower, comment or like) will have different markups. A follower notification will have a follow button, a comment notification will have a button that redirects to the photo that was liked etc.
SQL UNION requires the tables to have the same number of columns and the selected columns must have the same name.
No, it doesn't. Here table "a" has two columns, integer and varchar.
create table a (
a_id integer,
a_desc varchar(10)
);
insert into a values (1, 'aaaaaaaa'), (2, 'bbbbbbbb');
Table "b" has three columns, varchar, date, and char.
create table b (
b_id varchar(10),
created_date date,
unused char(1)
);
insert into b values ('xyz', '2014-01-01', 'x'), ('tuv', '2014-01-13', 'x');
The SQL union operator only requires that the SELECT clauses (not tables) have the same number of columns, and that they be of compatible data types. You can usually cast incompatible types to something more useful.
-- SELECT clause has three columns, but table "a" has only two.
-- The cast is for illustration; MySQL can union an integer with a
-- varchar without a cast.
--
select cast(a_id as char) as col_1, a_desc as col_2, null as col_3
from a
union all
-- Note that these columns don't have the same names as the columns
-- above.
select b_id, null, created_date
from b;
You can use a single column for date and varchar, but it's usually not a good idea. (Mixing dates with something that's clearly not a date is usually not a good idea.)
select cast(a_id as char) as col_1, a_desc as col_2
from a
union all
select b_id, created_date
from b;
You can use UNION but you'll need to use 'AS' to give columns the same name.
You'll also need to add a line like this to each select:
, 'comment' as Type FROM comment
and:
, 'follow' as Type FROM follow
Here is the situation i have two tables
of
idof, (somtother data)
---------------------
1, (somtother data)
2, (somtother data)
3, (somtother data)
and i have
ofc
id, ofid, idcat
------------------
1,1,1
1,1,2
1,2,1
1,3,3
Here is what i use to get all from first table and joint it with second
SELECT * FROM `of`
LEFT JOIN (`ofc`)
ON ( `of`.`idof` = `ofc`.`ofid` )
Now i want to get 5 rows from of (imagine that second table has more rows) for each idcat, and i cant seem to get the sql right. i have done till now
select * from `of` as `f`
JOIN `ofc` as `fa`
ON `f`.`idof`=`fa`.`ofid`
where (
select count(*) from `of` as `nf`
JOIN `ofc` as `nfa`
ON `nf`.`idof`=`nfa`.`ofid`
GROUP BY `nfa`.`idcat`
) <= 5;
Bit this subquery returns more than one row, and mysql complains. is there any other way to do this?without executing one query for each different idc?
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