How to select content from two different tables in Mysql? - mysql

How can I select the contents of two columns that reside in different tables in a mysql database?

You would need to use either a JOIN or UNION/UNION ALL.
This will depend on wht you require.
Lets say you want all values from table 1 col a and table 2 col b in seperate rows
You can use
SELECT ColA
FROM TABLE1
UNION ALL
SELECT ColB
FROM TABLE2
All Distinct Values
SELECT ColA
FROM TABLE1
UNION
SELECT ColB
FROM TABLE2
And lets say that the you want to display them in the same row, they should have some key that links them
SELECT ColA, ColB
FROM TABLE1 t1 INNER JOIN
TABLE2 t2 ON t1.ID = t2.ID
It would also be good to note that there are different types of Sql Joins
Different SQL JOINs
JOIN: Return rows when there is at
least one match in both tables
LEFT JOIN: Return all rows from the
left table, even if there are no
matches in the right table
RIGHT JOIN: Return all rows from the
right table, even if there are no
matches in the left table
FULL JOIN: Return rows when there is
a match in one of the tables

Use a JOIN.
http://w3schools.com/SQL/sql_join.asp

SELECT fields
FROM table_a a
JOIN table_b b
ON (a.id = b.foo_id)

Related

Specify table-column on "in" operator

i would like to know if there is any shortcut to specify the column where IN have to check for matches.
Example:
Instead of this:
select *
from table1
where id in(
select column
from table2
)
something like this:
select *
from table1
where id in table2.column
I know the existence of TABLE for IN, ANY, SOME to specify a table, but it works only if the table specified is composed by just 1 column
EDIT: using join is not an option, because the real use i was looking for is on a NOT IN operator, and also JOIN create duplicates sometimes like in a one to many relation
There is no shortcut like that in SQL. Let me explain why.
In a query, all table references need to be made in the FROM clause. Hence, you cannot simply refer to table2.col unless table2 has been defined in the FROM clause. table2 is actually an alias, which defaults to the table name.
From a performance perspective, I would recommend exists:
select t1.*
from table1 t1
where exists (select column
from table2 t2
where t2.column = t1.id
)
In particular, this can take advantage of an index on table2(column) and has the same semantics as in.
Using a JOIN is a bit shorter. At least it does not require a subquery or another SELECT ... FROM.
SELECT table1.*
FROM table1
JOIN table2 ON table1.id = table2.column
Although this simple example is an inner join, not a semi-join. An inner join is different because it produces one row per matched row in table2. A semi-join only produces one row for each row in table1, even if it matches multiple rows in table2.
If you want to simulate a semi-join, use DISTINCT to reduce the result to one row per row of table1:
SELECT DISTINCT table1.*
FROM table1
JOIN table2 ON table1.id = table2.column
If you want to check for something like NOT EXISTS, use an exclusion join:
SELECT table1.*
FROM table1
LEFT OUTER JOIN table2 ON table1.id = table2.column
WHERE table2.column IS NULL
No need to use DISTINCT on the outer join example. There will be no row duplication from the join, because it can only "match no rows" once.

Merge two tables to one and remove duplicates

I have 2 tables in the same database.
I want to merge them based on the common id column. Because the tables are too huge I am not sure if there are duplicates.
How is it possible to merge these two tables into one based on the id and be sure that there are no duplicates?
SELECT *
FROM table1,table2
JOIN
GROUP BY id
What do you mean by merging two tables? Do you want records and columns from both the tables or columns from one and records from both?
Either way you will need to change the join clause only.
You could do a join on the columns you wish to
SELECT DISTINCT *
FROM table1 tb1
JOIN table2 tb2
ON table1.id = table2.id
Now if you want columns from only table1 do a LEFT JOIN
If you want columns from only table2 then a RIGHT JOIN
If you want columns from both the tables, use the query as is.
DISTINCT ensures that you get only a single row if there are multiple rows with the same data (but this distinct will check values for all columns in a row whether they are different or the same)
Union won't help if both tables have different number of columns. If you don't know about joins then use a Cartesian product
select distinct *
from table1 tb1, table2 tb2
where tb1.id = tb2.id
Where id is the column that is common between the tables.
Here if you want columns from only table1 do
select distinct tb1.*
Similarly replace tb1 by tb2 in the above statement if you just want table2 columns.
select distinct tb2.*
If you want cols from both just write '*'
In either cases I.e. joins and products said above if you need selective columns just write a table alias. E.g.
Consider :
table1 has id, foo, bar as columns
table2 has id, name,roll no, age
you want only id, foo, name from both the tables in the select query result
do this:
select distinct tb1.id, tb1.foo, tb2.name
from table1 tb1
join table2 tb2
on tb1.id=tb2.id
Same goes for the Cartesian product query. tb1, tb2 are BTW called as a table aliases.
If you want data from both the tables even if they have nothing in common just do
select distinct *
from table1 , table2
Note that this cannot be achieved using a join as join requires a common column to join 'on'
I am not sure What exactly do you want but anyway, this is your code
SELECT *
FROM table1,table2
JOIN
GROUP BY id
i just edit your query
SELECT *
FROM table1 JOIN table2
on table2.id = table1.id
GROUP BY table1.id // here you have to add table
//on which you will be group by at this moment this is table1
Try UNION:
https://dev.mysql.com/doc/refman/5.0/en/union.html
IT is very simple. Hope it will help.
Also you should have a look at "DISTINCT".

MySQL Joins of tables with different columns

I want to create a table that needs to be a combination of selected columns from three or more tables. I don't have any sample data, just added the columns for explanation.
Table 1
A|B1|C1|D1|E1|F1|G1|H1|I1|J1
Table 2
A|B2|C2|D2|E2|F2|G2
Table 3
A|B3|C3|D3|E3|F3|G3
Resultant New table must have
A|B1|E1|F1|G1|J1|C2|D2|G2|B3|D3|F3
I'm not sure if I need to use a FULL JOIN or use UNIONS.
Each of these tables contain more than 400,000 rows. Any help here on what query needs to be included would be really helpful.
You can try the below query:
select t1.A,t1.B1,t3.E1,t1.F1,t1.G1,t1.J1,t2.C2,t2.D2,t2.G2,t3.B3,t3.D3,t3.F3
from table1 t1 join table2 t2 on t1.A = t2.A
join table3 t3 join table2 t2 on t3.A = t2.A
As Palec commented correctly in the other answer, so adding a bit of explanation to the answer.
You need to use the JOINS for this problem instead of UNION. The reason why I am saying to use JOINS over UNION is UNION combines the data/result of two or more queries into a single result set which includes all the rows which exist in the queries in your UNION. But when you are using JOINs, you can retrieve data from two or more tables based on logical relationships between the tables.
Also to add that you should add an alias name to your table so that it becomes easy to retrieve the column in the select query and also while linking the table.
Join is the correct way:
select table1.A,B1,E1,F1,G1,J1,C2,D2,G2,B3,D3,F3 from table1 join table2 on table1.A = table2.A
join table3 join table2 on table3.A = table2.A

SQL Count + Left join + Group by ... Missing rows

Trying to list all what's in table 1 and records under it in table 2
Table one each row has an id , and each row in table 2 has idontable1
select table1.*, count(table2.idintable1)as total
from table1
left join table2 on table1.id=table2.idintable1
WHERE table1.deleted='0' AND table2.deleted=0
group by
table2.idintable1
My current problem is rows from table1 with 0 records in table2 are not displayed
I want them to be displayed
The query that you want is:
select t1.*, count(t2.idintable1) as total
from table1 t1 left join
table2 t2
on t1.id = t1.idintable1 and t2.deleted = 0
where t1.deleted = 0
group by t1.id;
Here are the changes:
The condition on t2.deleted was moved to the on clause. Otherwise, this turns the outer join into an inner join.
The condition on t1.deleted remains in the where clause, because presumably you really do want this as a filter condition.
The group by clause is based on t1.id, because t2.idintable1 will be NULL when there are no matches. Just using t1.id is fine, assuming that id is unique (or a primary key) in table1.
The table aliases are not strictly necessary, but they make queries easier to write and to read.
You should GROUP BY table1.id.
The LEFT JOIN ensures all the rows from table1 appear in the result set. Those that do not have a pair in table2 will appear with NULL in field table2.idintable1. Because of that your original GROUP BY clause produces a single row for all the rows from table1 that do not appear in table2 (instead of one row for each row of table1).
You have fallen into mysql's non-standard group by support trap.
Change your group by to list all columns of table 1:
group by table1.id, table1.name, etc
or list the column positions of all table1 columns in the select:
group by 1, 2, 3, 4, etc
Or use a subquery to get the count vs the id, and join table1 to that.

Insert missing records from one table to another using mysql

I don't know why I am confused with this query.
I have two table: Table A with 900 records and Table B with 800 records. Both table need to contain the same data but there is some mismatch.
I need to write a mysql query to insert missing 100 records from Table A to Table B.
In the end, both Table A and Table B should be identical.
I do not want to truncate all the entries first and then do a insert from another table. So please any help is appreciated.
Thank you.
It is also possible to use LEFT OUTER JOIN for that. This will avoid subquery overhead (when system might execute subquery one time for each record of outer query) like in John Woo's answer, and will avoid doing unnecessary work overwriting already existing 800 records like in user2340435's one:
INSERT INTO b
SELECT a.* FROM a
LEFT OUTER JOIN b ON b.id = a.id
WHERE b.id IS NULL;
This will first select all rows from A and B tables including all columns from both tables, but for rows which exist in A and don't exist in B all columns for B table will be NULL.
Then it filter only such latter rows (WHERE b.id IS NULL),
and at last it inserts all these rows into B table.
I think you can use IN for this. (this is a simpliplification of your query)
INSERT INTO table2 (id, name)
SELECT id, name
FROM table1
WHERE (id,name) NOT IN
(SELECT id, name
FROM table2);
SQLFiddle Demo
AS you can see on the demonstration, table2 has only 1 records but after executing the query, 2 records were inserted on table2.
If it's mysql and the tables are identical, then this should work:
REPLACE INTO table1 SELECT * FROM table2;
This will insert the missing records into Table1
INSERT INTO Table2
(Col1, Col2....)
(
SELECT Col1, Col2,... FROM Table1
EXCEPT
SELECT Col1, Col2,... FROM Table2
)
You can then run an update query to match the records that differ.
UPDATE Table2
SET
Col1= T1.Col1,
Col2= T1.Col2,
FROM
Table T1
INNER JOIN
Table2 T2
ON
T1.Col1 = T2.Col1
Code also works when a group by and having clauses are used. Tested SQL 2012 (11.0.5058) Tab1 is source with new records, Tab 2 is the destination to be updated. Tab 2 also has an Identity column. (Yes folks, real world is not as neat and clean as the lab assignments)
INSERT INTO Tab2
SELECT a.T1,a.T2,a.T3,a.T4,a.Val1,a.Val2,a.Val3,a.Val4,-9,-9,-9,-9,MIN(hits) MinHit,MAX(hits) MaxHit,SUM(count) SumCnt, count(distinct(week)) WkCnt
FROM Tab1 a
LEFT OUTER JOIN Tab2 b ON b.t1 = a.t1 and b.t2 = a.t2 and b.t3 = a.t3 and b.t4 = a.t4 and b.val1 = a.val1 and b.val2 = a.val2 and b.val3 = a.val3 and b.val4 = a.val4
WHERE b.t1 IS NULL or b.Val1 is NULL
group by a.T1,a.T2,a.T3,a.T4,a.Val1,a.Val2,a.Val3,a.Val4 having MAX(returns)<4 and COUNT(distinct(week))>2 ;