mysql request across 2 tables - mysql

I have one database with two tables:
table1: "backup1"
table2: "backup2"
both tables has a structure like
id, backupid, userid, backup, info
I would like to do a simple MYSQL request to get a group of entries where
it shows me what userid is found in table1 and ALSO in table2 to see what users did backups in both tables
I know I could open table1 look for a userid and do a another MYSQL to see if its also
in table2, but I hope there is a simpler way to do that with a single request.

SELECT userid
FROM backup1
INNER JOIN backup2
USING(userid)
The inner join on the userid field will cause the query to only return rows that are found in both tables.

This isn't through '2 databases', this is through '2 tables'. Just use a join.
SELECT a.userid
from backup1 a
inner join backup2 b
on a.userid=b.userid
This will give you all userids in backup1 that also exist in backup2

if you only need to know if a user made a backup in both tables, you could simply use simple select statements. A simple example, using a temporary variable #uId to hold the Id of the user you want to check, and two temporary variables to hold the (boolean) answer for each table
set #uId = 1; -- The user Id
select
#b_t1 := (select count(*) from table1 where userId=#uId) > 0 as hasBackupOnTable1,
#b_t2 := (select count(*) from table2 where userId=#uId) > 0 as hasBackupOnTable2,
#b_t1 and #b_t2 as hasBackupOnBothTables;

Related

sql stored procedure with out duplicates name

How can I create a query to SELECT ALL DB WITHOUT duplicates
Like (old DB that is no longer in use c,f,g. basically if it does have eur and has an original name than it is relevant):
a
b
c
ceur
d
f
feur
g
geur
I need it to be like:
a
b
ceur
d
feur
geur
Many thanks...
SELECT DISTINCT
is what you're looking for. See more here.
For instance, let's say you have a table that contains the following rows:
name, city, address, country.
You now wish to get the countries that has been stored, without duplicates. Multiple people might come from the same country, and so the table would most likely have duplicate entries of that country.
How you achieve this is by using the SELECT DISTINCT.
Example:
SELECT DISTINCT country FROM table_name;
What this will do is retreive the country row without duplicates. That way, you can see which countries are actually stored in that table without duplicates.
If you have multiple databases (I don't know if that's what you were getting at), then you will need to perform a JOIN on the relevant tables, given you have access to them all. I would recommend doing a LEFT JOIN if you are to join more than just 1 extra table.
Example:
SELECT DISTINCT table_name.row_name, table_name.row_name2, table_name.row_name3
FROM table_name
LEFT JOIN table_name2 ON table_name.row_name = table_name2.row_name
LEFT JOIN table_name3 ON table_name2.row_name = table_name3.row_name
[...]
WHERE table.row_name = 'value';
Can you query information_schema.TABLES and distinct in the select, plus a predicate to filter out whatever you don't want?
You can do:
select t.*
from t
where name like '%eur'
union all
select t.*
from t
where not like '%eur' and
not exists (select 1 from t t2 where t2.name = concat(t.name, 'eur');

Joining two tables in mysql - One to many relationship

I have 2 tables in mysql - User (user_id, first_name ....) and login_history(user_id, login_time)
Every time an user loges in, system records the time in login_history.
I want to run a query to fetch all the fields from the users table and the latest login time from login_history . Can anyone help please?
You have to use a join then :
SELECT *, login_history.login_time
FROM User
INNER JOIN login_history
ON User.user_id=login_history.user_id;
And this query gonna give you, all the columns of User and the login_time.
SELECT t1.col1
,t1.col2
,[...repeat for all columns in User table]
,max(t2.login_time)
FROM user t1
INNER JOIN login_history t2 ON t1.user_id = t2.user_id
GROUP BY t1.col1
,t1.col2
,[..repeat for all columns in User table]
This should work, assuming login_time is stored in a sane data type and/or format.
Following are 2 queries that can help you out to select latest login time with user details
SELECT * FROM User C,login_history O where C.user_id=O.user_id order by O.login_time desc limit 1
or
SELECT * FROM User C,login_history O where C.user_id=O.user_id and ROWNUM <=1 order by O.login_time desc

Join multiple databases mysql

I have roughly 2 Million records in two different databases, each has 1 million. I want to join the two tables with each other to find the differences but due to the data size the mysql throws a time-out error each time i perform the action. This is my query:
SELECT id FROM db1.table1 AS a INNER JOIN db2.table1 AS b ON ( b.Id != a.Id )
Any help would be appreciated !
You are joining each db1 record with all db2 records that have another ID. So thats about a trillion rows generated.
Try the following instead:
select * from db1.table1 where id not in (select id from db2.table1);
and
select * from db2.table1 where id not in (select id from db1.table1);
or combined:
select 'db1' as db, * from db1.table1 where id not in (select id from db2.table1)
union all
select 'db2' as db, * from db2.table1 where id not in (select id from db1.table1);
Try to use MySQL subquery:
SELECT id FROM db1.table1 WHERE id NOT IN (SELECT id FROM db2.table1);
The above query consists of two parts. The first part which is inside parenthesis selects field id from db2.table1 without any limitation. This result will be used in the outer one to remove unwanted records from db1.table1.

Delete, Update with derived tables?

I have just studied FROM clause and derived tables in mysql and most of the websites provided the examples using SELECT command
Example SELECT * FROM (SELECT * FROM usrs) as u WHERE u.name = 'john'
But when I have tried using delete or update command it does not seem to work.
Example DELETE FROM (SELECT * FROM usrs) as u WHERE u.name = 'john'
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near (SELECT * FROM usrs) as u WHERE u.name = 'john' at line
UPDATE (SELECT * FROM usrs) as u SET u.lname ='smith' WHERE u.name = 'john'
1288 The target table e of the UPDATE is not updatable
So derived tables does not work with delete or update commands? or is there a way to make it work.
Instead of writing the table name for update and delete I want to write a subquery that gets the records and perform the delete operation on that records? Is that possible in mysql?
UPDATED I have to delete a record and i have three tables, the record may exist in any of the table
My approach delete from first table rows effected? quit: else check second table rows effected? quit : else check third table
But if I use UNION ALL I can do this way
Delete from (select * from tb1 union all select * from tb2 union all select * from tb3) e as e.uname = 'john'
but this query does not seem to work , now could anyone tell me how do i delete or update a record when i have more than one table to search. Any help is greatly appreciated.
You can't directly delete from the subquery, but you can still use it if you'd like, you'll just need to use it in a JOIN:
DELETE usrs
FROM usrs
INNER JOIN (
SELECT * FROM usrs WHERE name = 'john'
) t ON usrs.Id = t.Id
Or you could use IN:
DELETE usrs
WHERE ID IN (
SELECT ID
FROM usrs
WHERE name = 'John'
)
With this said, for this example, I don't know why you'd want a subquery:
DELETE usrs WHERE name = 'John'
Edit base on comments. To delete from multiple tables at the same time, you can either have multiple DELETE statements, or you can use something like the following:
delete t1, t2, t3
from (select 'john' as usr) t
left join t1 on t.usr=t1.usr
left join t2 on t.usr=t2.usr
left join t3 on t.usr=t3.usr
SQL Fiddle Demo
Derived tables exist only for the duration of the parent query they're a member of. Assuming that this syntax and the operations were allowed by MySQL, consider what happens:
a) Your main query starts executing
b) the sub-query executes and returns its results as a temporary table
c) the parent update changes that temporary table
d) the parent query finishes
e) temporary tables are cleaned up and deleted
Essentially you'll have done nothing except waste a bunch of cpu cycles and disk bandwidth.
UPDATE queries DO allow you to join against other tables to use in the WHERE clause, e.g..
UPDATE maintable
LEFT JOIN othertable ON maintable.pk = othertable.fk
SET maintable.somefield='foo'
WHERE othertable.otherfield = 'bar'

How to do mysql search which excludes duplicate records

I am trying to perform a search on a table with structure like
id, mls_id, address, agent_id. What I would like to do is pull all the records for agent_id but not pull more than one if there is same mls. For example:
Select * From table WHERE agent_ID = 1234
might pull up 5 records but let's say two of the records have an mls_id that is the same. Is there a way to just pull one of those and still keep all the other results in tact?
This seems to do the trick:
What it does is to choose the record with the minimal id from those that have the same mls_id
SELECT id, mls_id, address, agent_id
FROM MyTable t1
WHERE t1.agent_id=1 AND t1.id =
(SELECT Min(t2.id)
FROM MyTable t2
WHERE agent_id=1 AND t2.mls_id=t1.mls_id
GROUP BY t2.mls_id)
Here is the fiddle example : SqlFiddle
SELECT DISTINCT *
FROM table
WHERE agent_ID = 1234
Using the DISTINCT keyword will drop duplicate records from your result set.