MySQL Left join - no repeat for right side - php

I have
<table1>
column1 column2
1 A
2 B
2 C
<table2>
column3 column4
1 C
2 D
When I do left join
SELECT table1.column1,
table1.column2,
table2.column4
FROM table1
LEFT JOIN table2 ON table1.column1 = table2.column3
I get
column1 column2 column4
1 A C
2 B D
2 C D
Would it be possible to instead somehow get the output as,
column1 column2 column4
1 A C
2 B
2 C D
I want that for every repeated table1.column1, the table2.column4 should come only once and the remaining times it comes out blank.
I have tried various things but haven't succeeded in any.

give it a try
select
new_t1.column1, new_t1.column2, if(new_t1.get_value, t2.column4,'')
from
(select
t1.*, if(t1_tmp.column2 is null, 1, 0) as get_value
from table1 t1
left join table1 t1_tmp on t1.column1 = t1_tmp.column1 and t1.column2 < t1_tmp.column2
) as new_t1
left join table2 t2 on new_t1.column1 = t2.column3

Try this query:
select t4.column1,t4.column2,case when max2 is null
then null else t4.column4 end as column4 from
(select table1.column1, table1.column2, table2.column4,t3.* from table1
left join table2 on table1.column1 = table2.column3
left outer join
(select max2,max1 from
(select max(column2) max2,min(column2) min2,
max(column1) max1,min(column1) min1 from
(select table1.column1, table1.column2, table2.column4 from table1
left join table2 on table1.column1 = table2.column3)t1
group by column4)t2)t3
on table1.column1 = t3.max1 and table1.column2 = t3.max2)t4;
SQL Fiddle

Related

SELECT * FROM table1, table2, table3 [duplicate]

This question already has answers here:
SQL Inner-join with 3 tables?
(12 answers)
Closed 5 years ago.
I have a problem ...
In table1 I have an id, I have to compare that id in table2, then fetch the second id that is in table2 and compare it to table3 and get as a result a datum.
Example
TABLE1
ID NAME ECC...
1 Jhon
2 Frank
TABLE2
ID ID2 ECC..
1 4
2 8
TABLE3
ID NAME
4 Sea
8 Hello
If I look for id 1, the result must be Sea
If I look for id 2 the result must be Hello
Thanks!
SELECT Table3.NAME
FROM Table1
INNER JOIN Table2
ON Table1.ID = Table2.ID
INNER JOIN Table3
ON Table3.ID = Table2.ID2
WHERE Table1.ID = 1 -- Your Search here
You should use joins.
Your query will look like :
SELECT t3.name
FROM table3 t3
LEFT JOIN table2 t2 ON t3.id = t2.id2
LEFT JOIN table1 t1 ON t2.id2 = t1.id
WHERE t1.id = <your_number>
select Table2.Id,Table3.Name from Table1 inner join Table2 on Table2.ID2 = Table3.Id
Query:
SELECT a.name As Name FROM table3 a JOIN
(SELECT b.id2 AS id FROM table1 a JOIN table2 b ON a.id = b.id)b
ON a.id = b.id where b.id = <your id number (1,2) Anything>
Should be something like this:
select table3.name as name3
from table3
where table3.ID = table2.ID2
and table2.ID = table1.ID
and table1.ID = <YOURNUMBERHERE>

SQL query want to eliminate the same data in multiple tables

**Table :1** **Table:2**
id folio num num1 num2 num3 num4 num5 id number folio
-------------------
------------------------------------------
1 abcde 1000 2000 3000 4000 5000 0 1 6000 abcde
2 1000 abcde
2 abcde 6000 3 7000 abcde
4 5000 abcde
5 10000 abcde
output want to be
id number folio
---------------
1 7000 abcde
2 10000 abcde
----------------------
I USED THE SQL QUERY OF
SELECT * FROM Table2 WHERE id_t = 'abcde'
AND number NOT IN(SELECT CONCAT(num,num1,num2,num3,num4,num5) FROM Table1 WHERE id_t = 'abcde')
-----------------------------------------------
SQL query want to eliminate the same data in multiple tables.
Want to compare two table but different fields ,if data in that table it want to eliminate only the unique data want to show
1.table2 number(field) want to check table1 num,num1,num2,num3,num4,num5(field)
2.values which was not in table 1 alone want to display
Doing a LEFT OUTER JOIN on a sub query. The sub query returns every num for each folio.
The WHERE clause then ensures only rows are returned where there is no match (ie, nothing matching found in the sub query).
SELECT Table2.id,
Table2.number,
Table2.folio
FROM Table2
LEFT OUTER JOIN
(
SELECT folio, num AS aNum FROM table1
UNION
SELECT folio, num1 AS aNum FROM table1
UNION
SELECT folio, num2 AS aNum FROM table1
UNION
SELECT folio, num3 AS aNum FROM table1
UNION
SELECT folio, num4 AS aNum FROM table1
UNION
SELECT folio, num5 AS aNum FROM table1
) sub0
ON Table2.folio = sub0.folio
AND Table2.number = sub0.num
WHERE sub0.folio IS NULL
Alternative that might make better use of index:-
SELECT Table2.id,
Table2.number,
Table2.folio
FROM Table2
LEFT OUTER JOIN table1 t1a ON Table2.folio = t1a.folio AND Table2.number = t1a.num
LEFT OUTER JOIN table1 t1b ON Table2.folio = t1b.folio AND Table2.number = t1b.num1
LEFT OUTER JOIN table1 t1c ON Table2.folio = t1c.folio AND Table2.number = t1c.num2
LEFT OUTER JOIN table1 t1d ON Table2.folio = t1d.folio AND Table2.number = t1d.num3
LEFT OUTER JOIN table1 t1e ON Table2.folio = t1e.folio AND Table2.number = t1e.num4
LEFT OUTER JOIN table1 t1f ON Table2.folio = t1f.folio AND Table2.number = t1f.num5
WHERE COALESCE(t1a.num, t1b.num1, t1c.num2, t1d.num3, t1e.num4, t1f.num5) IS NULL
EDIT
Another way to do it, although not keen on this one. Uses a sub query to concatenate up all the values of the various num fields, and then GROUP_CONCAT to do that over various lines. Then joins against that using FIND_IN_SET. Likely to be inefficient, but for amusement here it is:-
SELECT Table2.id,
Table2.number,
Table2.folio
FROM Table2
LEFT OUTER JOIN
(
SELECT folio, GROUP_CONCAT(CONCAT_WS(',', num, num1, num2, num3, num4, num5)) AS all_num
FROM table1
GROUP BY folio
) sub0
ON Table2.folio = sub0.folio
AND FIND_IN_SET(Table2.number, sub0.all_num) > 0
WHERE sub0.folio IS NULL

Outer Join Giving Fatal error [duplicate]

I want to do a full outer join in MySQL. Is this possible? Is a full outer join supported by MySQL?
You don't have full joins in MySQL, but you can sure emulate them.
For a code sample transcribed from this Stack Overflow question you have:
With two tables t1, t2:
SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
The query above works for special cases where a full outer join operation would not produce any duplicate rows. The query above depends on the UNION set operator to remove duplicate rows introduced by the query pattern. We can avoid introducing duplicate rows by using an anti-join pattern for the second query, and then use a UNION ALL set operator to combine the two sets. In the more general case, where a full outer join would return duplicate rows, we can do this:
SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION ALL
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
WHERE t1.id IS NULL
The answer that Pablo Santa Cruz gave is correct; however, in case anybody stumbled on this page and wants more clarification, here is a detailed breakdown.
Example Tables
Suppose we have the following tables:
-- t1
id name
1 Tim
2 Marta
-- t2
id name
1 Tim
3 Katarina
Inner Joins
An inner join, like this:
SELECT *
FROM `t1`
INNER JOIN `t2` ON `t1`.`id` = `t2`.`id`;
Would get us only records that appear in both tables, like this:
1 Tim 1 Tim
Inner joins don't have a direction (like left or right) because they are explicitly bidirectional - we require a match on both sides.
Outer Joins
Outer joins, on the other hand, are for finding records that may not have a match in the other table. As such, you have to specify which side of the join is allowed to have a missing record.
LEFT JOIN and RIGHT JOIN are shorthand for LEFT OUTER JOIN and RIGHT OUTER JOIN; I will use their full names below to reinforce the concept of outer joins vs inner joins.
Left Outer Join
A left outer join, like this:
SELECT *
FROM `t1`
LEFT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`;
...would get us all the records from the left table regardless of whether or not they have a match in the right table, like this:
1 Tim 1 Tim
2 Marta NULL NULL
Right Outer Join
A right outer join, like this:
SELECT *
FROM `t1`
RIGHT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`;
...would get us all the records from the right table regardless of whether or not they have a match in the left table, like this:
1 Tim 1 Tim
NULL NULL 3 Katarina
Full Outer Join
A full outer join would give us all records from both tables, whether or not they have a match in the other table, with NULLs on both sides where there is no match. The result would look like this:
1 Tim 1 Tim
2 Marta NULL NULL
NULL NULL 3 Katarina
However, as Pablo Santa Cruz pointed out, MySQL doesn't support this. We can emulate it by doing a UNION of a left join and a right join, like this:
SELECT *
FROM `t1`
LEFT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`
UNION
SELECT *
FROM `t1`
RIGHT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`;
You can think of a UNION as meaning "run both of these queries, then stack the results on top of each other"; some of the rows will come from the first query and some from the second.
It should be noted that a UNION in MySQL will eliminate exact duplicates: Tim would appear in both of the queries here, but the result of the UNION only lists him once. My database guru colleague feels that this behavior should not be relied upon. So to be more explicit about it, we could add a WHERE clause to the second query:
SELECT *
FROM `t1`
LEFT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`
UNION
SELECT *
FROM `t1`
RIGHT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`
WHERE `t1`.`id` IS NULL;
On the other hand, if you wanted to see duplicates for some reason, you could use UNION ALL.
Using a union query will remove duplicates, and this is different than the behavior of full outer join that never removes any duplicates:
[Table: t1] [Table: t2]
value value
----------- -------
1 1
2 2
4 2
4 5
This is the expected result of a full outer join:
value | value
------+-------
1 | 1
2 | 2
2 | 2
Null | 5
4 | Null
4 | Null
This is the result of using left and right join with union:
value | value
------+-------
Null | 5
1 | 1
2 | 2
4 | Null
SQL Fiddle
My suggested query is:
select
t1.value, t2.value
from t1
left outer join t2
on t1.value = t2.value
union all -- Using `union all` instead of `union`
select
t1.value, t2.value
from t2
left outer join t1
on t1.value = t2.value
where
t1.value IS NULL
The result of the above query that is as the same as the expected result:
value | value
------+-------
1 | 1
2 | 2
2 | 2
4 | NULL
4 | NULL
NULL | 5
SQL Fiddle
#Steve Chambers: [From comments, with many thanks!]
Note: This may be the best solution, both for efficiency and for generating the same results as a FULL OUTER JOIN. This blog post also explains it well - to quote from Method 2: "This handles duplicate rows correctly and doesn’t include anything it shouldn’t. It’s necessary to use UNION ALL instead of plain UNION, which would eliminate the duplicates I want to keep. This may be significantly more efficient on large result sets, since there’s no need to sort and remove duplicates."
I decided to add another solution that comes from full outer join visualization and math. It is not better than the above, but it is more readable:
Full outer join means (t1 ∪ t2): all in t1 or in t2
(t1 ∪ t2) = (t1 ∩ t2) + t1_only + t2_only: all in both t1 and t2 plus all in t1 that aren't in t2 and plus all in t2 that aren't in t1:
-- (t1 ∩ t2): all in both t1 and t2
select t1.value, t2.value
from t1 join t2 on t1.value = t2.value
union all -- And plus
-- all in t1 that not exists in t2
select t1.value, null
from t1
where not exists( select 1 from t2 where t2.value = t1.value)
union all -- and plus
-- all in t2 that not exists in t1
select null, t2.value
from t2
where not exists( select 1 from t1 where t2.value = t1.value)
SQL Fiddle
None of the previous answers are actually correct, because they do not follow the semantics when there are duplicated values.
For a query such as (from this duplicate):
SELECT * FROM t1 FULL OUTER JOIN t2 ON t1.Name = t2.Name;
The correct equivalent is:
SELECT t1.*, t2.*
FROM (SELECT name FROM t1 UNION -- This is intentionally UNION to remove duplicates
SELECT name FROM t2
) n LEFT JOIN
t1
ON t1.name = n.name LEFT JOIN
t2
ON t2.name = n.name;
If you need this to work with NULL values (which may also be necessary), then use the NULL-safe comparison operator, <=> rather than =.
MySQL does not have FULL-OUTER-JOIN syntax. You have to emulate it by doing both LEFT JOIN and RIGHT JOIN as follows:
SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
But MySQL also does not have a RIGHT JOIN syntax. According to MySQL's outer join simplification, the right join is converted to the equivalent left join by switching the t1 and t2 in the FROM and ON clause in the query. Thus, the MySQL query optimizer translates the original query into the following -
SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT * FROM t2
LEFT JOIN t1 ON t2.id = t1.id
Now, there is no harm in writing the original query as is, but say if you have predicates like the WHERE clause, which is a before-join predicate or an AND predicate on the ON clause, which is a during-join predicate, then you might want to take a look at the devil; which is in details.
The MySQL query optimizer routinely checks the predicates if they are null-rejected.
Now, if you have done the RIGHT JOIN, but with WHERE predicate on the column from t1, then you might be at a risk of running into a null-rejected scenario.
For example, the query
SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
WHERE t1.col1 = 'someValue'
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
WHERE t1.col1 = 'someValue'
gets translated to the following by the query optimizer:
SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
WHERE t1.col1 = 'someValue'
UNION
SELECT * FROM t2
LEFT JOIN t1 ON t2.id = t1.id
WHERE t1.col1 = 'someValue'
So the order of tables has changed, but the predicate is still applied to t1, but t1 is now in the 'ON' clause. If t1.col1 is defined as NOT NULL
column, then this query will be null-rejected.
Any outer-join (left, right, full) that is null-rejected is converted to an inner-join by MySQL.
Thus the results you might be expecting might be completely different from what the MySQL is returning. You might think its a bug with MySQL's RIGHT JOIN, but that’s not right. Its just how the MySQL query optimizer works. So the developer in charge has to pay attention to these nuances when he/she is constructing the query.
I modified shA.t's query for more clarity:
-- t1 left join t2
SELECT t1.value, t2.value
FROM t1 LEFT JOIN t2 ON t1.value = t2.value
UNION ALL -- include duplicates
-- t1 right exclude join t2 (records found only in t2)
SELECT t1.value, t2.value
FROM t1 RIGHT JOIN t2 ON t1.value = t2.value
WHERE t1.value IS NULL
In SQLite you should do this:
SELECT *
FROM leftTable lt
LEFT JOIN rightTable rt ON lt.id = rt.lrid
UNION
SELECT lt.*, rl.* -- To match column set
FROM rightTable rt
LEFT JOIN leftTable lt ON lt.id = rt.lrid
You can do the following:
(SELECT
*
FROM
table1 t1
LEFT JOIN
table2 t2 ON t1.id = t2.id
WHERE
t2.id IS NULL)
UNION ALL
(SELECT
*
FROM
table1 t1
RIGHT JOIN
table2 t2 ON t1.id = t2.id
WHERE
t1.id IS NULL);
You can just convert a full outer join, e.g.
SELECT fields
FROM firsttable
FULL OUTER JOIN secondtable ON joincondition
into:
SELECT fields
FROM firsttable
LEFT JOIN secondtable ON joincondition
UNION ALL
SELECT fields (replacing any fields from firsttable with NULL)
FROM secondtable
WHERE NOT EXISTS (SELECT 1 FROM firsttable WHERE joincondition)
Or if you have at least one column, say foo, in firsttable that is NOT NULL, you can do:
SELECT fields
FROM firsttable
LEFT JOIN secondtable ON joincondition
UNION ALL
SELECT fields
FROM firsttable
RIGHT JOIN secondtable ON joincondition
WHERE firsttable.foo IS NULL
SELECT
a.name,
b.title
FROM
author AS a
LEFT JOIN
book AS b
ON a.id = b.author_id
UNION
SELECT
a.name,
b.title
FROM
author AS a
RIGHT JOIN
book AS b
ON a.id = b.author_id
I fix the response, and works include all rows (based on the response of Pavle Lekic):
(
SELECT a.* FROM tablea a
LEFT JOIN tableb b ON a.`key` = b.key
WHERE b.`key` is null
)
UNION ALL
(
SELECT a.* FROM tablea a
LEFT JOIN tableb b ON a.`key` = b.key
where a.`key` = b.`key`
)
UNION ALL
(
SELECT b.* FROM tablea a
right JOIN tableb b ON b.`key` = a.key
WHERE a.`key` is null
);
Use:
SELECT * FROM t1 FULL OUTER JOIN t2 ON t1.id = t2.id;
It can be recreated as follows:
SELECT t1.*, t2.*
FROM (SELECT * FROM t1 UNION SELECT name FROM t2) tmp
LEFT JOIN t1 ON t1.id = tmp.id
LEFT JOIN t2 ON t2.id = tmp.id;
Using a UNION or UNION ALL answer does not cover the edge case where the base tables have duplicated entries.
Explanation:
There is an edge case that a UNION or UNION ALL cannot cover. We cannot test this on MySQL as it doesn't support full outer joins, but we can illustrate this on a database that does support it:
WITH cte_t1 AS
(
   SELECT 1 AS id1
   UNION ALL SELECT 2
   UNION ALL SELECT 5
   UNION ALL SELECT 6
   UNION ALL SELECT 6
),
cte_t2 AS
(
     SELECT 3 AS id2
   UNION ALL SELECT 4
   UNION ALL SELECT 5
   UNION ALL SELECT 6
   UNION ALL SELECT 6
)
SELECT  * FROM  cte_t1 t1 FULL OUTER JOIN cte_t2 t2 ON t1.id1 = t2.id2;
This gives us this answer:
id1  id2
1  NULL
2  NULL
NULL  3
NULL  4
5  5
6  6
6  6
6  6
6  6
The UNION solution:
SELECT  * FROM  cte_t1 t1 LEFT OUTER JOIN cte_t2 t2 ON t1.id1 = t2.id2
UNION    
SELECT  * FROM cte_t1 t1 RIGHT OUTER JOIN cte_t2 t2 ON t1.id1 = t2.id2
Gives an incorrect answer:
id1  id2
NULL  3
NULL  4
1  NULL
2  NULL
5  5
6  6
The UNION ALL solution:
SELECT  * FROM cte_t1 t1 LEFT OUTER join cte_t2 t2 ON t1.id1 = t2.id2
UNION ALL
SELECT  * FROM  cte_t1 t1 RIGHT OUTER JOIN cte_t2 t2 ON t1.id1 = t2.id2
Is also incorrect.
id1  id2
1  NULL
2  NULL
5  5
6  6
6  6
6  6
6  6
NULL  3
NULL  4
5  5
6  6
6  6
6  6
6  6
Whereas this query:
SELECT t1.*, t2.*
FROM (SELECT * FROM t1 UNION SELECT name FROM t2) tmp
LEFT JOIN t1 ON t1.id = tmp.id
LEFT JOIN t2 ON t2.id = tmp.id;
Gives the following:
id1  id2
1  NULL
2  NULL
NULL  3
NULL  4
5  5
6  6
6  6
6  6
6  6
The order is different, but otherwise matches the correct answer.
Use a cross join solution:
SELECT t1.*, t2.*
FROM table1 t1
INNER JOIN table2 t2
ON 1=1;
It is also possible, but you have to mention the same field names in select.
SELECT t1.name, t2.name FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT t1.name, t2.name FROM t2
LEFT JOIN t1 ON t1.id = t2.id
The SQL standard says full join on is inner join on rows union all unmatched left table rows extended by nulls union all right table rows extended by nulls. Ie inner join on rows union all rows in left join on but not inner join on union all rows in right join on but not inner join on.
Ie left join on rows union all right join on rows not in inner join on. Or if you know your inner join on result can't have null in a particular right table column then "right join on rows not in inner join on" are rows in right join on with the on condition extended by and that column is null.
Ie similarly right join on union all appropriate left join on rows.
From What is the difference between “INNER JOIN” and “OUTER JOIN”?:
(SQL Standard 2006 SQL/Foundation 7.7 Syntax Rules 1, General Rules 1 b, 3 c & d, 5 b.)

How to make an Order By a field but with a condition inside?

Please masters, I have three table, that I need to select data from using a LEFT JOIN;
and that I need to order by a field q (that exists in table3) but only where state = 1 (that exists also in table3).
I tried this but it doesn't work :
SELECT * FROM table 1
LEFT JOIN table2 ON x = y
LEFT JOIN table3 ON z=w
WHERE w = 1
ORDER BY q IN ( SELECT q FROM table3 WHERE state = 1);
Please any suggestions ?
How abt this:
SELECT * FROM table 1
LEFT JOIN table2 ON x = y
LEFT JOIN table3 ON z=w
WHERE w = 1
ORDER BY case when state=1 then 0 else 1 end,q
Try this:
SELECT *,
(SELECT q FROM table3 WHERE state = 1) as sort_order
FROM table 1
LEFT JOIN table2 ON x = y
LEFT JOIN table3 ON z=w
WHERE w = 1
ORDER BY sort_order
As I do not know what the desired result should be, possibly this is the right query:
SELECT *
FROM table1 as t1
LEFT JOIN table2 as t2 ON t1.x = t2.y
LEFT JOIN table3 as t3 ON t2.z = t3.w AND t3.state = 1
WHERE t3.w = 1
ORDER BY t3.q
Try something like that :
SELECT * FROM table 1
LEFT JOIN table2 ON x = y
LEFT JOIN table3 ON z=w
WHERE w = 1 AND table3.state = 1
ORDER BY q

How can I build this query to compare a id with two tables?

I have drawn this image to explain what I need
1.to compare a user_id with the user_id's in two different tables
2.the corresponding ref_global_id from both the tables are then matched to a events table
3.matching global_id's from the events table are then arranged in ascending order.
Or this:
SELECT e.global_id, e.event_time
FROM (SELECT * FROM table1
UNION
SELECT * FROM table2) x inner join
event_table e ON e.global_id = x.ref_global_id
WHERE x.[user_id] = 121
SELECT e.global_id, e.event_time
FROM events_table e
JOIN table1 t1 on e.global_id = t1.ref_global_id
JOIN table2 t2 on e.global_id = t2.ref_global_id
WHERE t1.user_id = 121 AND t2.user_id = 121
ORDER BY e.event_time
Try this:
select global_id, event_time from event left join table1 on event.global_id = table1.ref_global_id AND table1.user_id = 121 left join table2 on event.global_id = table2.ref_global_id AND table2.user_id = 121

Categories