SQL Join where column a in table 1 matches a value from 1 of 4 columns (a-d) in table 2 - mysql

Goal:
Trying to join together two tables
Table structure:
t1:
name | id
t2:
id_a | id_b | id_c | id_d | favorite color
Problem:
I'm trying to find out the favorite color that corresponds to each name, where the t1.id is found in 1 of the 4 id fields in t2. The tricky part is that the non-matching values aren't null, so a coalesce doesn't work.
What I've tried:
Tried a case when statement in the join, but that seems to be creating some endless loop that is never finishing.
Trying a union, but that is creating some unexpected duplication.
Also tried a multi- on condition (like below), but that's not working:
WITH test AS (
SELECT
t1.*
, t2.*
FROM t1
LEFT JOIN t2
ON ( t1.id = t2.id_a
OR t1.id = t2.id_b
OR t1.id = t2.id_c
OR t1.id = t2.id_d
)
)
SELECT COUNT(*) FROM test
;
Here's an example dataset:
WITH names AS(
SELECT
1 as id , 'alfred' as name
UNION ALL SELECT 2, 'becca'
UNION ALL SELECT 3, 'charlie'
UNION ALL SELECT 4, 'dezi'
)
, color AS(
SELECT
1 as id_a, 6 as id_b, 9 as id_c, 7 as id_d, 'green' as fave_color
UNION ALL SELECT 1,2,6,5, 'orange'
UNION ALL SELECT 5,7,9,3, 'blue'
UNION ALL SELECT 9,4,6,8, 'black'
)
SELECT
n.id
, n.name
, c.fave_color
FROM color c
LEFT JOIN names n
ON n.id IN (c.id_a,c.id_b,c.id_c,c.id_d)
GROUP BY 1,2,3
ORDER BY 1,2
;

Related

Can I select rows from two tables using t1 rows as key for t2 rows?

I have two tables:
id1, id2, ... idX contains id from t2 or null. Can I make such select, which will put params from t2 in t1?
For example i have a t1(name,year,id1,id2,id3,id4) values:
name year id1 id2 id3 id4
------------------------------------------
marko 1999 1 2 null 1
polo 1985 null null 5 3
And t2 values:
id info param
--------------------------------------
1 apple green
2 car yellow
3 bee pink
4 doctor whiskey
5 book small
So I'd like to have such dynamical query results, based on t1 rows:
SELECT name, year, id1-info, id1-param, id2-info, id2-param, id4-info, id4-param
FROM t1 WHERE name = 'marko'
SELECT name, year, id3-info, id3-param, id4-info, id4-param
FROM t1 WHERE name = 'marko'
I googled a lot, but found nothing except nested queries, such as:
SELECT
name,
year,
(SELECT `info` FROM t2 WHERE id = t1.id1) AS id1-info,
(SELECT `param` FROM t2 WHERE id = t1.id1) AS id1-param,
(SELECT `info` FROM t2 WHERE id = t1.id2) AS id2-info...
But I understand, that it is a very bad idea, because I have a lot of id columns in t1, which are not static. Or if it cannot be done dynamically, can I just make SELECT, which will show me all in one row:
SELECT name, year, id1-info, id1-param, id2-info, id2-param, id3-info, id3-param, id4-info, id4-param
FROM t1 WHERE name = 'marko'
To use one select in one row, you can use mulitple left join on t2.
SELECT name,
`year`,
id11.info as `id1-info`,
id11.param as `id1-param`,
id21.info as `id2-info`,
id21.param as `id2-param`,
id31.info as `id3-info`,
id31.param as `id3-param`,
id41.info as `id4-info`,
id41.param as `id4-param`
FROM t1
LEFT JOIN t2 as id11 on t1.id1=id11.id
LEFT JOIN t2 as id21 on t1.id2=id21.id
LEFT JOIN t2 as id31 on t1.id3=id31.id
LEFT JOIN t2 as id41 on t1.id4=id41.id
WHERE name = 'marko';
result:
name year id1-info id1-param id2-info id2-param id3-info id3-param id4-info id4-param
marko 1999 apple green car yellow (null) (null) apple green

how to exclude first and last row if group it on particular id

I have sample table with data like this
id uniqueid values
1 6 0
2 6 1
3 6 2
4 6 0
5 6 1
I want result like this
id uniqueid values
2 6 1
3 6 2
4 6 0
I tried like this
select id,uniqueid,values
FROM t1
WHERE
id not in(SELECT concat(MAX(message_id_pk),',',min(message_id_pk)) FROM t1
where uniqueid=6)
and `uniqueid`=6
GROUP BY uniqueid
but its not working
You can achieve the desired results by doing self join, Inner query will get the the max and min ids for per group and outer query will filter out the results by using minid and maxid
select a.*
from demo a
join (
select `uniqueid`,min(id) minid, max(id) maxid
from demo
where uniqueid=6
group by `uniqueid`
) b using(`uniqueid`)
where a.id > b.minid and a.id < b.maxid /* a.id <> b.minid and a.id <> b.maxid */
Demo
Also you can do it by using 2 sub-queries with EXISTS to exclude the min and max id of each uniqueid.
Query
select `id`, `uniqueid`, `values`
from `your_table_name` t1
where exists (
select 1 from `your_table_name` t2
where t2.`uniqueid` = t1.`uniqueid`
and t2.`id` > t1.`id`
)
and exists(
select 1 from `your_table_name` t2
where t2.`uniqueid` = t1.`uniqueid`
and t2.`id` < t1.`id`
);
Here is a sql fiddle demo
Try this -
SELECT id, uniqueid, values
FROM YOUR_TABLE
WHERE id NOT IN (MIN(id), MAX(id));

JOIN, GROUP BY, SUM Issue Mysql

Assuming I have this table
tableA
ID value
1 5
1 5
3 10
2 4
2 2
1 2
tableB
ID Name
1 apple
2 carrot
3 banana
If the expected max value of apple is 10, carrot is 5, and banana is 15 the output table would be
table output
ID Name value
1 apple 12
2 carrot 6
what SQL statement I need to solve this?
what I have done so far:
SELECT a,ID, b.name , sum(a.valueSUM) AS value FROM tableA a
INNER JOIN tableB b
ON a.id = b.id
GROUP BY id
what options i need on the WHERE clause to pull this off?
The inner subquery groups them normally and then the main query is what deals with limiting the results.
SELECT * FROM
(select
b.id,
b.name as name,
SUM(a.value) as the_sum
from tableA a inner join tableB b
on a.Id = b.id
group by b.name, b.id
) y
where (name = 'apple' and the_sum >= 10) OR
(name = 'banana' and the_sum >= 15) OR
(name = 'carrot' and the_sum >= 5)
It seems your sample data has changed, please try this. I thought the ID doesnt have to follow tableA/tableB's id and the id is auto-generated as per the results.
Would be nice if you have another table that sets the threshold per name
Assuming threshold can be specified in tableB (makes sense):
SELECT a.ID, b.name, sum(a.value) AS value
FROM tableA a
INNER JOIN tableB b
ON a.id = b.id
GROUP BY a.ID, b.name, b.Threshold
HAVING sum(a.value) > b.Threshold;
Demo: http://rextester.com/ICOQF10295
SELECT TableB.id, TableB.Name, MAX(TableA.value) AS Value
FROM TableA INNER JOIN TableB ON
TableA.id = TableB.id
GROUP BY TableB.id, TableB.Name
Instead of SUM, use MAX aggregate function
This works in SQL Server
--Existing tables
create table #tableA (ID int, value int)
create table #tableB (ID int, Name varchar(30))
insert into #tableA
select 1 , 5 union all
select 1 , 5 union all
select 3 , 10 union all
select 2 , 4 union all
select 2 , 2 union all
select 1 , 2
insert into #tableB
select 1 , 'apple' union all
select 2 , 'carrot' union all
select 3 , 'banana'
--Create new temporary table #tableC
create table #tableC (ID int, MAXvalue int)
insert into #tableC
select 1 , 10 union all
select 2 , 5 union all
select 3 , 15
select c.ID,b.Name, a.value from #tableC c
inner join #tableB b on b.ID = c.ID
inner join (
select ID,SUM(value) as value from #tableA
group by ID
) a on a.ID = c.ID
where a.value >= c.MAXvalue
drop table #tableA
drop table #tableB
drop table #tableC

Mysql update max value with group by

I have a simple table that has many rows already:
id grade ...
1 1 ...
2 2 ...
3 2 ...
4 1 ...
5 1 ...
Now i want to add a column "relative_order", which is the order in that grade. So the table becomes:
id grade ... relative_order
1 1 ... 1
2 2 ... 1
3 2 ... 2
4 1 ... 2
5 1 ... 3
After i add the column, all the relative_order becomes 0 first. How can i fill the relative_order column using update syntax?
I tried using inner join, but failed:
UPDATE table AS i
INNER JOIN(
SELECT max(relative_order) as mOrder,grade
FROM table
GROUP BY grade
) AS j
ON i.grade = j.grade
SET i.relative_order = j.mOrder + 1
You could use this SELECT query that will return the relative_order that you need:
SELECT
t1.id,
t1.grade,
COUNT(t2.id) relative_order
FROM
yourtable t1 INNER JOIN yourtable t2
ON t1.grade=t2.grade AND t1.id>=t2.id
GROUP BY
t1.id,
t1.grade
or if you want to update the value, you can join your table with the previous query, like this:
UPDATE
yourtable INNER JOIN (
SELECT
t1.id,
t1.grade,
COUNT(t2.id) relative_order
FROM
yourtable t1 INNER JOIN yourtable t2
ON t1.grade=t2.grade AND t1.id>=t2.id
GROUP BY
t1.id,
t1.grade) seq
ON yourtable.id=seq.id AND yourtable.grade=seq.grade
SET
yourtable.relative_order = seq.relative_order
Please see fiddle here.

UPDATE FROM SELECT with foreign key on parent with one query

How to update (change from first select table value second) second_table.first_table_id if first_table.email match in both select.
If it even possible. With one query!
----------------------------------------- UPDATE -----------------------------------------
EXAMPLE:
I need to update foreign key of second table if email field match in first table. I need to compare two query results with different parent_id (parents are in in same table with children)
table_1
-------------------------
| id | parent_id | email |
-------------------------
1 NULL NULL
2 NULL NULL
3 1 joe#m.ru
4 2 bob#f.ly
5 1 bob#f.ly
6 2 kira#.us
table_2
----------------
| id | first_id |
----------------
1 3
2 4
3 5
4 6
I have two parents with ids 1 and 2 and some children (ids: 3,4,5,6).
Also, keep in mind: 1 - old, 2 - new
Task: change foreign key in second table if children email with parent_id = 1 and chilren email with parent_id = 2 match (are the same).
In our example in second table row with id = 3 its foreign key field - first_id has to change from 5 to 4.
Following might get you started
UPDATE Table_2 t2u
SET first_id = (
SELECT t2.first_id
FROM Table_2 t2
INNER JOIN Table_1 t1 ON t1.id = t2.first_id
INNER JOIN (
SELECT parent_id = MAX(parent_id), email
FROM Table_1
GROUP BY
email
) t1p ON t1p.email = t1.email
INNER JOIN Table_1 t1i ON t1i.email = t1p.email
AND t1i.parent_id = t1p.parent_id
WHERE t2u.first_id <> t1i.id)
Test script (SQL Server)
;WITH Table_1 (id, parent_id, email) AS (
SELECT 1, NULL, NULL
UNION ALL SELECT 2, NULL, NULL
UNION ALL SELECT 3, 1, 'joe#m.ru'
UNION ALL SELECT 4, 2, 'bob#f.ly'
UNION ALL SELECT 5, 1, 'bob#f.ly'
UNION ALL SELECT 6, 2, 'kira#.us'
)
, Table_2 (id, first_id) AS (
SELECT 1, 3
UNION ALL SELECT 2, 4
UNION ALL SELECT 3, 5
UNION ALL SELECT 4, 6
)
SELECT t2.*, t1i.id as [update with]
FROM Table_2 t2
INNER JOIN Table_1 t1 ON t1.id = t2.first_id
INNER JOIN (
SELECT parent_id = MAX(parent_id), email
FROM Table_1
GROUP BY
email
) t1p ON t1p.email = t1.email
INNER JOIN Table_1 t1i ON t1i.email = t1p.email
AND t1i.parent_id = t1p.parent_id
WHERE t2.first_id <> t1i.id
Output
id first_id update with
----------- ----------- -----------
3 5 4