MySQL Query - Getting distinct values - mysql

There is a table "T" that contains data as shown below:
A B
---------
3 5
4 6
7 10
8 5
9 12
3 6
3 7
8 7
Assuming a given input set of {3,8} as values for A, how to retrieve all distinct values of B for which all values in the input set has an entry?
B
---
5
7
EDIT: I think the question is not clear enough. I want values in B which have a record with all values in the given set as a value for column A. So, B=6 will not be included since there is no record with A=8 and B=6. Hope this makes it clear!

SELECT DISTINCT B
FROM my_table WHERE A IN (3,8)
EDIT:
SELECT B FROM AB WHERE A = 3
INTERSECT
SELECT B FROM AB WHERE A = 8
INTERSECT give you the rows which occurs in both resultsets.
2nd EDIT:
SELECT B,COUNT(B)
FROM AB WHERE A IN (3,8)
GROUP BY B
HAVING COUNT(B) = 2
You should however modify this in two places: in IN arguments and on the end, in COUNT(B) = ?. ? should be equal the number of the arguments. I hope this will help.
3rd EDIT:
SELECT B,COUNT(B)
FROM
(
SELECT DISTINCT A, B FROM AB
) x
WHERE A IN (3,8)
GROUP BY B
HAVING COUNT(B) = 2
This will avoid the duplicate entries problem.

Basically, you can create two subqueries where you filter out only the rows that are candidates for matching (i.e. A is either 3 or 8). Then join those rows with each other on the value of B, and any matching rows will be what you're looking for. I'm not 100% certain of the syntax for MySQL, but I believe this will work:
SELECT *
FROM (SELECT * FROM T WHERE A = 3) t3
INNER JOIN (SELECT * FROM T WHERE A = 8) t8 ON t3.B = t8.B

Related

Get count of all types of values in a column obtained in the same SELECT SQL query

MySQL Version: 5.7.36
I'm attempting to minimize the amount of queries I have to execute.
Right now, I'm executing a query similar to this:
SELECT
TABLE 1.column1 as "A",
TABLE 1.column2 as "B"
FROM
TABLE 1
WHERE
CONDITION
I can obtain the results I need from this query, however I would also like to obtain the count of what type of values show up in the same query.
For example, if the following query retrieves this table
A B
- -
1 a
1 b
1 c
2 d
3 e
4 f
4 g
I would also like to, for each row, obtain the count of all rows retrieved with its column "A" that matches its value.
Would it be more efficient to execute another query to get that result or can I modify my obtaining query to get this statistic?
Desired result:
A B C
- - -
1 a 3 # 3 rows with "1" in Column "A"
1 b 3
1 c 3
2 d 1
3 e 1
4 f 2
4 g 2
UPDATE:
The closest query I could find goes like this:
SELECT
TABLE 1.column1 as "A",
COUNT(TABLE 1.column1)
FROM
TABLE 1
WHERE
TABLE 1.column1 = "foo"
GROUP BY
TABLE 1.column1
Results in this:
A B C
- - -
1 a 3
2 d 1
3 e 1
4 f 2
However, it removes any other rows with the same value in column "A". Even if it has different values in column "B". I would like to have all rows present in my SQL query with its corresponding row count.
The next closest query I found goes like this:
SELECT
TABLE 1.column1 as "A",
COUNT(TABLE 1.column1)
FROM
TABLE 1
WHERE
TABLE 1.column1 = "foo"
GROUP BY
TABLE 1.column2
Results in this:
A B C
- - -
1 a 1
1 b 1
1 c 1
2 d 1
3 e 1
4 f 1
4 g 1
Which also isn't achieving the desired result.
You have to join with the subquery that gets the counts.
SELECT t1.column1 AS A, t1.column2 AS B, t2.count
FROM Table1 AS t1
JOIN (
SELECT column1 AS A, COUNT(*) AS count
FROM Table1
GROUP BY column1
) AS t2 ON t1.A = t2.A
SELECT
c,
COUNT(*) OVER (PARTITION BY c)
FROM t
ORDER BY c

Update value of one table with summed value of related table by using intermediate table

I have three tables A, A_B and B.
Since mySQL doesn't support many to many relationships, tables A and B are related to each other by intermediate table A_B.
Table A: Table A_B: Table B:
aId aCount aId bId bId bCo
1 10 1 1 1 4
2 15 1 2 2 5
3 20 2 1 3 6
3 2 4 7
3 4
Now I want to add bCount of each bId to each related aCount.
Desired result:
Table A: Remark:
aId aCount (Current aCount + all related bCounts)
1 19 (10 + 4 + 5)
2 19 (15 + 4)
3 32 (20 + 5 + 7)
My mySQL knowledge is too basic.
I can create a SELECT query which gives me a result table like i want table A to look like after update, but I can't create the update statement. Everything I tried led to syntax errors or undesired results.
I also had one statement which might had work, but it took way to long to execute. Now I'm just confused about what to do.
Desired Result looks like:
SELECT `aId`, aCount + SUM(`bCount`) as `aCount` from `A`
INNER JOIN `A_B` ON `A_B`.`aId` = `A`.`aId`
INNER JOIN `B` ON `B`.`bId` = `A_B`.`bId`
GROUP BY `aId`;
Is an update like I want even possible with a single query or do I need multiple (performance wise)?
Can anyone help me out with an approach or with creating statements?
Try below: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=0b6a287d41eed001710e94612c4228ba
select x.id,x.val,sum(tableb.val)+x.val as vals from
(select * from tablea inner join tableab on tablea.id=tableab.id1) x inner join
tableb on x.id2=tableb.id
group by x.id,x.val,id1
Output:
id val vals
1 10 19
2 15 19
3 20 32
To update tablea:
UPDATE tablea INNER JOIN
(SELECT x.id, x.val, SUM(tableb.val) + x.val as vals FROM
(SELECT * FROM tablea INNER JOIN tableab ON tablea.id = tableab.id1) x INNER JOIN
tableb ON x.id2 = tableb.id
GROUP BY x.id, x.val, id1)Z ON tablea.id=Z.id
SET tablea.val = Z.vals;

SQL Query - Find Duplicates with a Different Key

I have the following data:
id userid name group
1 1 A x
2 1 A y
3 1 A z
4 2 B x
5 2 B y
6 3 C y
7 4 D x
8 5 E x
9 5 E z
10 6 F x
I want to find those records that meet all this condition:
Select all rows where the a userid belongs to a group other than y but the userid also belongs to group y.
The resulting dataset will be as follows:
id userid name group
1 1 A x
3 1 A z
4 2 B x
If you see, it has resulted in two records for userid a because these are two two records belong to groups other than y but the userid 1 also belongs to group y. Same for userid 2.
I have been breaking my head on how to get this in an SQL statement but not even close to a solution.
Any help is appreciated.
Use a join:
SELECT t1.*
FROM mytable t1
INNER JOIN mytable t2
ON t1.user_id = t2.user_id AND t1.group <> t2.group AND t2.group = 'y'
I think that would be the fastest query (but please feel free to try the other solutions as well).
Add an index on user_id if not already there and maybe play with some other indexes as well (maybe a composite index on group and user_id can be utilized)
Use exists
select *
from MyTable a2
where name_group <> 'y'
and exists (select 1
from MyTable a2
where a2.name_group = 'y'
and a2.userid = a1.userid)
You can get all the users that meet the condition using aggregation and having:
select userid
from t
group by userid
having sum( group = 'y' ) > 0 and
sum( group <> 'y') > 0;
I leave it to your to put this into a query to get all the original rows.

MySQL: JOIN tables and return a column from a row depending on an aggregate function on another column [duplicate]

This question already has answers here:
How can I SELECT rows with MAX(Column value), PARTITION by another column in MYSQL?
(22 answers)
Closed 6 years ago.
Let there be two tables:
Table A
id | name
1 x
2 y
Table B
foreign_key | value | external
1 1 60
1 2 50
2 3 80
2 4 90
The desired result is a JOIN looking like this:
id | name | external
1 x 50
2 y 90
i.e., for each row in A we get the corresponding external from B where value is max for a given id.
What I have so far is this:
SELECT
A.`id`,
A.`name`,
B.`external`
FROM `A`
LEFT JOIN `B`
ON A.id = B.foreign_key
GROUP BY id
This obviously returns the first B.external encountered instead of the one with the highest value:
id | name | external
1 x 60
2 y 80
Is there a way to achieve this, preferably without using subqueries?
Not sure why dont want sub-query but Correlated sub-query looks simpler to me
select id, name,
(Select external
from TableB B where A.id = B.foreign_key Order by Value desc Limit 1 )
From TableA A
If you want to achieve this using JOIN then you may have to join the TableB twice

how to SELECT and Concat() column values based on several conditions SQL query?

newbie here to SQL. So I have two tables, let's take for example the two tables below.
Table A
set_num s_id s_val
100 3 AA
100 5 BB
200 3 AA
200 9 CC
Table B
s_id s_val phrase seq
1 DD 'hi' 'first'
3 AA 'hello' 'first'
6 EE 'goodnight' 'first'
5 BB 'world' 'second'
9 CC 'there' 'second'
4 FF 'bye' 'first'
I want to join Table A with Table B on two columns, like a composite key (s_id, s_val), and I want to return
set_num from Table A and the concatenation of phrases in Table B (which we will call entire_phrase, concat(...) AS entire_phrase).
The concatenation should also follow an order in which the phrases are to be concatenated. This will be determined by seq column in Table B for each phrase. "First" will indicate this phrase needs to come first and "Second", well comes next. I will like to do this with a SELECT query but not sure if this is possible without it getting to complex. Can I do this in SELECT or does this call for another approach?
Expected Output:
set_num entire_phrase
100 'hello world'
200 'hello there'
And not
set_num entire_phrase
100 'world hello'
200 'there hello'
Any help/approach will be greatly appreciated!
You can do it like this:
select temp1.set_num, concat(phrase1,' ',phrase2) as entire_phrase
from (
(
select set_num, b.phrase as phrase1
from TableA as A
join TableB as B
on a.s_id = b.s_id
and a.s_val = b.s_val
and b.seq = 'first'
) as temp1
join
(
select set_num, b.phrase as phrase2
from TableA as A
join TableB as B
on a.s_id = b.s_id
and a.s_val = b.s_val
and b.seq = 'second'
) as temp2
on temp1.set_num = temp2.set_num
)
Running here: http://sqlfiddle.com/#!9/d63ac3/1