MySQL merge queries when using foreign keys - mysql

Is there a quick way to select results based on constraints from one table and use the foreign keys obtained from this to select results in the parent table? Or can you only do this with two separate queries?
So achieves the same as this, but in one query (tableB has a foreign key from tableA):
Query1: SELECT * FROM tableB WHERE columnN LIKE x
Query2: SELECT * FROM tableA WHERE primaryKey LIKE foreignKeyFromQuery1

Select columns in a table and other to get single result mean JOIN.
you can use this:
SELECT <Table>.<Field>, <Table>.<Field> FROM <Table 1>
INNER JOIN <Table 2> ON <Table 1>.<Primary Key>=<Table 2>.<Foreign Key>
WHERE <Conditions>
Based on your need, it looks you need INNER JOIN:
Query1: SELECT * FROM tableB WHERE columnN LIKE x
Query2: SELECT * FROM tableA WHERE primaryKey LIKE foreignKeyFromQuery1
The joins will be like this:
SELECT * FROM tableB INNER JOIN tableA ON
tableB.primaryKey=tableA.foreignKeyFromQuery1 WHERE columnN LIKE x

If you mean joining tables, then you would do it like this:
SELECT table1.column_name, …
FROM table1
JOIN table2 ON join_condition
You use the syntax join table_to_join on join_condition to join tables where references are consistent. Normally the join condition is something like ON table1.id = table2.id. In this way, the data is combined without duplicating rows.

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.

two tables query with same primary key

I have two tables with same primary key name "codigo",
I try to make a mysql query to combine both results on new one table.
SELECT * FROM recuperacion.inventario, recuperacion.Salidas where codigo='5ae2399f4fbd3';
this query is not work.
You need to join the tables.
SELECT *
FROM recuperacion.inventario
INNER JOIN recuperacion.Salidas USING (codigo)
WHERE codigo='5ae2399f4fbd3';
The USING clause can be used when the joining relationship is the same column name(s) in both tables. This then allows you to refer to that column without qualifying it with a table prefix.
SELECT t1.*, t2.*
-- INTO NewTableName
FROM recuperacion.inventario t1
INNER JOIN recuperacion.Salidas t2
ON t1.codigo = t2.codigo
WHERE t1.codigo='5ae2399f4fbd3'
NOTE: this will get you all columns from both tables. If you only want specific columns you need to edit the select list. Just be sure to use the aliases.
you have to use join
SELECT *
FROM recuperacion.inventario tab1
INNER JOIN recuperacion.Salidas tab2
on tab1.codigo = tab2.codigo
where tab1.codigo='5ae2399f4fbd3'
Use a JOIN syntax for the query:
SELECT *
FROM recuperacion.inventario a JOIN recuperacion.Salidas b
ON a.codigo = b.codigo
WHERE a.codigo='5ae2399f4fbd3';

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 LEFT JOIN in CASE?

I have a table where I want to join different tables depending on the value of one column, like so (this doesn't work, but it's my example):
SELECT * FROM table1
JOIN (CASE WHEN table1_column1=1 THEN table2 ON table2_column1=table1_column2 END)
WHERE table1_column3='hello'
All in all there are gonna be 4 values in the column, calling other tables. Is this doable?
Edit: I think I need to clarify what I'm after. Depending on the value of table1_column1, I want the JOIN to fetch a specific table and column. For example, if t1c1=1 it should join table2_column1 on table1_column2. If, however, t1c1=2 it should join table5_column1 on table1_column2. Etc, etc, etc.
Again - is this doable? It's easily scripted if I use two separate queries. I just want to use one query, however.
SELECT * FROM
table1 JOIN table2 ON table2_column1=table1_column2 AND table1_column1=1
UNION
SELECT * FROM
table1 JOIN table3 ON table2_column1=table1_column2 AND table1_column3='hello'
it might work
SELECT * FROM table1
JOIN table2 ON table2_column1=table1_column2 and table1_column1=1
WHERE table1_column3='hello'

Joining a subselect to a table in sql

Is it possible to join the results of a SELECT with another table.
Like this:
SELECT * FROM table1 LEFT OUTER JOIN (SELECT * FROM table 2)
I know I need to link the column but am not sure how. Is this possible?
You need to know what columns you are joining on. Assuming they are called ID in both tables, something like this would work:
SELECT *
FROM table1 t1
LEFT OUTER JOIN (SELECT * FROM table 2) t2 on t1.ID = t2.ID
Note that rather than using *, you should name the columns you need explicitly. This will give a more efficient query if you do not need all of the data, and will also prevent duplicate column names from being returned.
You can do this. The code would be something like:
(SELECT id as leftid, [other fields] FROM table1) LEFT OUTER JOIN (SELECT id rightid, [other fields] FROM table2) ON (leftid=rightid)
I didn't test it, though...