Find difference between tables where values differ - sqlite

When I search for how to compare two tables in SQLite, and see what's differ, I mostly find answers like this:
SELECT B.id FROM B LEFT JOIN A ON B.id = A.id WHERE A.id IS NULL
and yes, it's correct if you want do find all the elements (or values for keys named 'id' in this case) in table B that is not in table A, i.e. all the new elements in B if B is a later version of A.
But what if I want to find all the id:s in B where the value for a certain key (or keys) deviate from the corresponding value in A? For example, if I have two tables, A and B with id:s and positions, and I want to get the result id=3 in this case, because it is the element in B that has a value that differ. What would be the easiest way to do that?
Table A Table B
id | x_value | y_value id | x_value | y_value
----------------------- -----------------------
1 | 29.9563 | 12.6764 1 | 29.9563 | 12.6764
2 | 45.5843 | 7.6733 2 | 45.5843 | 7.6733
3 | 28.2313 | 15.6579 3 | 39.2003 | 15.6579
Result:
id
--
3

You can do it with a inner join with your condition in the where clause.
select a.id
from tableA a join tableB b on a.id = b.id
where ifnull(a.x_value, 0) <> ifnull(b.x_value, 0)
or ifnull(a.y_value, 0) <> ifnull(b.y_value, 0)

You can use INTERSECT:
LiveDemo
SqlFiddleDemo
SELECT tA.id
FROM TableA tA
JOIN TableB tB
ON tA.id = tB.id
WHERE NOT EXISTS( SELECT tA.x_value, tA.y_value
INTERSECT
SELECT tB.x_value, tB.y_value);
I like this solution, because it is easy to extend. Just add new column names. No need to handle NULL manually.

I agree with shawnt00 that you can read the question that the goal was to find all the id:s where values have changed between the two tables AND id:s of new instances inserted to the second table. Here is the select-statement to accomplish that, if anyone is interested:
select b.id
from b left join a on b.id = a.id
where ifnull(a.x_value, 0) <> ifnull(b.x_value, 0)
or ifnull(a.y_value, 0) <> ifnull(b.y_value, 0)
or a.id is null;

Related

DQL - JOIN WITH properties of a relation

My question is similar to this, but different.
Can you join on a subquery with Doctrine 2 DQL?
I want to get all the rooms regardless, and left join any occupants who belong to a booking that exists on a given date.
For example (a plain mysql result set - doctrine would return objects):
Room ID | Occupant ID | Booking ID | Booking Start | Booking End
1 | 1 | 1 | Before today | After today
1 | 2 | 1 | Before today | After today
2 | NULL | NULL | NULL | NULL
Here's what I'm trying:
SELECT r, a, b
FROM MyBundle:Room r
LEFT JOIN r.occupants a
WITH a.booking is not null
LEFT JOIN a.booking b
WITH b.enrolmentStart <= :date
AND b.enrolmentEnd >= :date
AND b.status = 1
ORDER BY r.number ASC
Unfortunately, this gets all the rooms, with all the people who ever stayed in that room ever, but only the bookings that exist on that given date.
On the other hand, if I change to the following,
I'm given only rooms that have bookings on that given date.
LEFT JOIN r.occupants a
WITH a.booking is not null
JOIN a.booking b
If I try the following, Doctrine says it didn't expect a dot after the 'a'.
LEFT JOIN r.occupants a
WITH a.booking.enrolmentStart <= :date
AND a.booking.enrolmentEnd >= :date
AND a.booking.status = 1
LEFT JOIN a.booking b
And lastly, if I try the following, doctrine is not happy about the order.
LEFT JOIN r.occupants a
WITH b.enrolmentStart <= :date
AND b.enrolmentEnd >= :date
AND b.status = 1
LEFT JOIN a.booking b
Any ideas?
I think that you can achieve this query only using left joins:
SELECT
r.number, o.id_occupant, b.id_booking, b.enrolmentStart, b.enrolmentEnd
FROM
MyBundle:Room r
LEFT JOIN r.occupants o
LEFT JOIN o.booking b
AND b.status = 1
AND b.enrolmentEnd >= :date
AND b.enrolmentStart <= :date
ORDER BY r.number ASC
Take a look to this equivalent sql (SQL Fiddle) query.
Debugged sql:
select r.number, ref.id_occupant, ref.id_booking
from rooms r
LEFT JOIN (select * from rooms r2
left join occupants o on o.room = r2.id_room
left join booking b on b.id_booking = o.booking
where b.status = 1
and b.enrolmentEnd >= '2015/03/09'
and b.enrolmentStart <= '2015/03/10') as ref on r.id_room = ref.id_room

SQLite subquery: "IN" the result of the outer query

I have two tables user and pair. I want to get the number of duplicate pairs (a, b) for each user.name.
user
name | id
-------------
"Alice" | 0
"Bob" | 1
"Alice" | 2
pair
id | a | b
-----------
0 | 0 | 1
0 | 1 | 3
1 | 0 | 1
2 | 1 | 3
In the above example, the result should be:
name | id | c
-------------------
"Alice" | 0,2 | 1
"Bob" | 1 | 0
When there is only one id for each user, I can do this:
SELECT name, id, (
SELECT COUNT(*) FROM pair JOIN pair AS p USING (id, a, b)
WHERE id = user.id AND pair.rowid < p.rowid
) AS c FROM user;
When there is multiple ids, I can get the correct result from the below query, but it is quite slow when there is more rows and more subqueries.
SELECT name, GROUP_CONCAT(id), (
WITH t AS (SELECT id FROM user AS u WHERE name = user.name)
SELECT COUNT(*) FROM pair JOIN pair AS p USING (a, b)
WHERE pair.id IN t AND p.id IN t AND pair.rowid < p.rowid
) AS c FROM user GROUP BY name;
I want to know that is there a simple and efficient way for this, like changing the WHERE clause from pair.id = user.id to pair.id IN <<the user.id list>>?
/* This will not work! "Error: no such table: user.id" */
SELECT name, GROUP_CONCAT(id), (
SELECT COUNT(*) FROM pair JOIN pair AS p USING (a, b)
WHERE pair.id IN user.id AND p.id IN user.id AND pair.rowid < p.rowid
) AS c FROM user GROUP BY name;
The GROUP BY name operation can be sped up if the database is able to go through the rows in order, without having to sort the table.
This can be done with an index on the name column (the other column makes this a covering index, which helps only a little more):
CREATE INDEX user_name_id_index ON user(name, id);
The query looks up pair rows by their id, a, and b values; these lookups can be sped up with an index on these columns:
CREATE INDEX pair_id_a_b_index ON pair(id, a, b);
To help the query optimizer make better decisions when selecting indexes, run ANALYZE.
The query optimizer gets improved constantly; get the newest SQLite version, if possible.
To check how your queries are executed, look at the output of the EXPLAIIN QUERY PLAN command.

How to concatenate a selection of sqlite columns spread over multiple tables?

I am aware that you can concatenate multiple columns within a single table with a query like this:
SELECT ( column1 || column2 || column3 || ... ) AS some_name FROM some_table
Is it possible to concatenate columns from multiple tables with a single sqlite query?
Very simple example - Two tables and the result:
Table1 | Table2 | Result
Col1 Col2 | Col3 |
-------------------------------------------------------------------------------
A B | C | ABC
If this is possible, what would the query be?
I can always manually concatenate multiple single table concatenation results, but having sqlite do all the work would be great:)
Try this
SELECT a.col1 || a.col2 || b.col3 AS 'SUM'
FROM table1 a, table2 b
WHERE a.id = b.id;
In where you have top mention the joining condition between the tables
Fiddle

UPDATE multiple rows using SELECT

I have A table and two rows with id=1 and id=2 and their x parameter is 1. I also have B table and two rows with same id 1 and 2. I am trying to update all of the data(column)on B table which has same id with A table whose x parameter is 1.
A table
id | x |
1 | 1 |
2 | 1 |
B table
id | Y |
1 | yes|
2 | yes|
My query is
UPDATE B SET y='No' WHERE B.id=(SELECT A.id FROM A WHERE A.x=1);
The problem is select returns mutliple data and i can only update the first data.
I tried to use JOIN but sqlite gives syntax error near INNER i couldn't find the problem.
UPDATE B SET B.y='No' INNER JOIN A ON B.id=A.id WHERE A.x=1;
Use this:
UPDATE ... WHERE B.id IN (SELECT A.id ...);

SQLite Select data from multiple rows returned as one row

I would like to know whether it is possible to use a SELECT statement in SQLite to merge the data from two rows into one, similar to how is suggested in the SQL Server forum below.
Consider the scenario below which is based on SQL Server (taken from http://forums.aspfree.com/microsoft-sql-server-14/merge-the-two-rows-in-one-row-245550.html)
Given there is a table
Emp
ID | Name |
1 | x |
1 | P |
2 | y |
2 | Q |
3 | W |
We want the resulting data from the select statement to output:
Emp_Data
Id | Name-1 | Name-2 |
1 | x | P |
2 | y | Q |
3 | w | |
The answer in the post suggests the following SQL as a possible solution:
SELECT
a.ID,
[Name-1] = ISNULL((
SELECT TOP 1 Name
FROM emp
WHERE ID = a.ID),''),
[Name-2] = ISNULL((
SELECT TOP 1 b.Name
FROM emp b
WHERE b.ID = a.ID
AND Name NOT IN(
SELECT TOP 1 Name
FROM emp
WHERE ID = b.ID
)),'')
FROM emp a
GROUP BY a.ID
Using SQLite is it possible to generate the columns [Name-1] & [Name-2] using nested SELECT statements like we can do above in SQL Server?
SELECT
a.ID,
COALESCE(a.Name,'') as "Name-1",
COALESCE((SELECT b.Name FROM Emp b
WHERE b.ID = a.ID
AND b.rowid != a.rowid LIMIT 1),'') as "Name-2"
FROM emp a
GROUP BY a.ID
Doug's solution didn't work for me. The code below, however, did work for me but it's very slow...
SELECT
a.ID,
a.Name AS Name1,
(SELECT b.Name FROM Emp b
WHERE b.ID = a.ID
AND b.Name != a.Name LIMIT 1) AS Name2
FROM emp a
GROUP BY a.ID
try this:::
select id, group_concat(name) from emp group by id;
;)

Resources