mySQL, three tables: UPDATE multiple rows (each with a different value) - mysql

I have three tables in mySQL:
TABLE:CollectionAttributeValues
cID
akID
avID
TABLE: atDefault
avID
value
TABLE: CollectionVersions
cID
cvName
Looks Like
CollectionVersions
cID cvName
1 Billete
5 Tony
atDefault
avID value
1 B.B
3 T.T
CollectionAttributeValues
cID akID avID
1 29 1
5 29 3
I need to take all the values (the column named values) in atDefault"
and put it into cvName in CollectionVersions
WHERE akID = 29 in CollectionAttributeValues
Basically, take "Billette" and change it to "B.B". AND also take "Tony" and change it to "TT".
So far I came up with this
SELECT value
FROM `atDefault` AS d
LEFT JOIN `CollectionAttributeValues` AS v ON d.avID = v.avID
WHERE v.akID =29
But I don't know how to insert the resulting values into the "cvName" column in CollectionVersions...

To UPDATE all the columns of the table CollectionVersions with the data that you get form the query. Try the below query -
UPDATE CollectionVersions cv
SET cvName =
(SELECT value
FROM `atDefault` AS d
LEFT JOIN `CollectionAttributeValues` AS v ON d.avID = v.avID
WHERE v.akID =29
AND cv.cID = v.cID)

Related

MySQL join two tables and add extra columns

I have three tables as shown below. The topics_table is to be created by inserting values from grades_table and subjects_table and a few other fields that are either taken in as input(topic_name) or calculated(revision dates).
grades_table
grade_id
grades
sections
1
1
A
2
1
B
subjects_table
subject_id
grade_id
teacher_id
subject_name
1
1
1
Maths
2
2
2
English
topics_table (NOTE: this table is currently empty).
I want to add values of grade_id and subject_id from the grades and subjects table to this table. Basically, I am thinking of joining the subject table and grades table and extracting the required values from that and put it in this table under grade id and subject id columns while also putting in topic_name from the user and revision dates from the system.
topic_id
grade_id
subject_id
topic_name
revision_one
revision_two
revision_three
1
1
1
Adding Fractions
28-10-2021
28-11-2021
28-12-2021
2
2
2
Nouns
01-11-2021
01-12-2021
01-01-2022
Right now, I am using join to insert the values of grade_id and subject_id in the topics_table, but the issue is that I am not able to receive the topic_name and revision dates as they are extra columns that cannot be taken from another table using joins.
Below is the MySQL query that I'm using to obtain topics_table right now. It only gives grade_id and subject_id.
How do I also get the extra columns?
Note that this table will be updated each time using the same query when the input for topic_name is entered.
Here, $chooseGrade, $chooseSubject, $chooseSection are the inputs that I will be receiving from the user via a form. $teacherId is received from another table using a different query.
Let me know if there is another way of taking in values from grades table and subjects table and putting it in the topics table. I tried to use SQL variables but even that didn't work. The code for that is also given.
INSERT INTO topics_table (subject_id, grade_id, $topicName , CURRENT_DATE(),CURRENT_DATE()+INTERVAL 1 DAY,CURRENT_DATE()+INTERVAL 7 DAY,CURRENT_DATE()+INTERVAL 30 DAY,CURRENT_DATE()+INTERVAL 90 DAY,CURRENT_DATE()+ INTERVAL 180 DAY)
SELECT G.grade_id, S.subject_id
FROM grades_table G
INNER JOIN subjects_table S
WHERE G.grade_id = S.subject_id
AND G.grades = $chooseGrade
AND G.sections = $chooseSection
AND S.subject_name = $chooseSubject
AND S.teacher_id = $teacherId
//using variables NOT joins
SELECT grade_id INTO #grade_id FROM grades_table WHERE grades = '$chooseGrade' AND sections = '$chooseSection';
SELECT subject_id INTO #subject_id FROM subjects_table WHERE grade_id = #grade_id AND subject_name = '$chooseSubject' AND teacher_id = '$teacherId';
INSERT INTO topics_table ( subject_id, grade_id, topic_name, revision_one, revision_two, revision_three) VALUES (#subject_id, #grade_id,'$topicName',CURRENT_DATE()+INTERVAL 30 DAY,CURRENT_DATE()+INTERVAL 60 DAY,CURRENT_DATE()+ INTERVAL 90 DAY);
you will have noticed that i replaced the variable with placeholders
See pleasr this topic about sql injection
Another thing is you joining form your query doesn't seem that correct to me, because Grades and subject should be referenced by grades_id and not be subject_id
the same goes for topics_table grades_id, seems also redundant, so you should take a look at normalisation
SELECT G.grade_id, S.subject_id,t.topic_name,t.revision_one, t.revision_two , t.revision_three
FROM grades_table G
INNER JOIN subjects_table S ON G.grade_id = S.grade_id
INNER JOIN topics_table t ON t.grade_id = s.grade_id AND t.subject_id = s.subject_id
WHERE G.grades = ?
AND G.sections = ?
AND S.subject_name = ?
AND S.teacher_id = ?
You should use merge if you want to get a single table as output
MERGE Subject S
USING Grade G
ON (S.SubjectID = G.GradeID)
WHEN MATCHED
THEN UPDATE SET
COLUMNAME = COLUMNNAME,
COLUMNNAME = COLUMNANAME
WHEN NOT MATCHED BY TARGET
THEN INSERT (XYZ, ABC, ABZ)
VALUES(XYZ,ABC,ABZ)
WHEN NOT MATCHED BY SOURCE
THEN DELETE
note: use your own values in place of xyz,abc etc

Subtract value of the same column with different where clauses and various rows

I Need help, I saw similar questions here, but no one helped me to solve this query.
I want to subtract values of the same column but with different where clauses but with various rows like this:
I Want to subtract this values so the output need to be like this:
Table with where clause 1
Product | Qty_totally| Name
PRODUCT A 10 HORGE
PRODUCT B 20 OMINION
PRODUCT C 30 LIKT
Table with where clause 2
Product | Qty_totally| Name
PRODUCT A 25 HORGE
PRODUCT B 50 OMINION
PRODUCT C 70 LIKT
Table with Final query
Product | Qty_totally| Name
PRODUCT A -15 HORGE
PRODUCT B -30 OMINION
PRODUCT C -40 LIKT
Help me please!!!!
I've tried this:
select descrição as 'Produto', sum(Quantidade_Total) as 'Quantidade_Entrada',Controle_armazem.Fornecedor as 'Fornecedor Controle Armazem' from Controle_armazem join produtos on controle_armazem.Modelo = produtos.idProdutos where Controle_armazem.Ativo = 1 and nota_fiscal is not null and nota_fiscal <> '' and defeito = 'Beneficiamento' AND situação = 'Beneficiado - Disponível para uso' GROUP BY descrição,Controle_armazem.fornecedor
Select descrição AS 'Produto', sum(Quantidade_Total) 'Quantidade Enviada', beneficiamento.Fornecedor as 'Fornecedor' From BeneficiamentoJoin controle_armazem On idPalete = palete join produtos on controle_armazem.Modelo = produtos.idProdutos WHERE Controle_armazem.Ativo = 1 And Beneficiamento.Ativo = 'A' GROUP BY descrição,Beneficiamento.fornecedor
I don't know how to subtract the value of "Quantidade_Total" column.
You'd simply join both queries. As there can be products in query #1 that are not in the results of query #2 and vice versa, you'd want a full outer join that MySQL does not provide. The best approach should be then to select from the products table and outer join both queries to it.
select
q1.product,
coalesce(q1.qty_totally, 0) - coalesce(q2.qty_totally, 0) as qty_totally,
q1.name as name1,
q2.name as name2
from produtos p
left join (query #1 here) q1 on q1.product = p.descrição
left join (query #2 here) q2 on q2.product = p.descrição
where q1.product is not null or q2.product is not null;

My SQL query involving multiple tables

I have 2 tables. First table stores id in multiple column whose value is stored in other table. I want a query that returns result which has structure of my 1st table but values from 2nd table. To be more specific let's say I have a table like this:
Table A:
Uniqueid song_1 song_2 song_3 song_4 song_5
1 2 4 5 6 8
Table B:
song_id song_name
1 abcd
2 def
3 efg
4 ghi
5 abdal
6 nsadln
7 knwldn
8 jdkabdb
I want to fetch data from Table A but it should look like:
Desired result:
Uniqueid song_1 song_2 song_3 song_4 song_5
1 def ghi abdal nsadln jdkabdb
I have used join and making objects but no luck so far. Please help me out.
Just use a bunch of left joins to get to your answer:
SELECT
a.UniqueId
,s1.song_name as song_1
,s2.song_name as song_2
,s3.song_name as song_3
,s4.song_name as song_4
,s5.song_name as song_5
FROM
TableA a
LEFT JOIN TableB s1
ON a.song_1 = s1.song_id
LEFT JOIN TableB s2
ON a.song_2 = s2.song_id
LEFT JOIN TableB s3
ON a.song_3 = s3.song_id
LEFT JOIN TableB s4
ON a.song_4 = s4.song_id
LEFT JOIN TableB s5
ON a.song_5 = s5.song_id

join or select in on multiple fields

(The example that follows is hypothetical, but illustrates the concept).
Using MySQL, say I have 2 tables:
userFromID userToId moreInfo
1 2 cat
1 3 dog
4 1 bear
3 4 fish
And...
userId someInfo addlInfo
1 m 32
2 f 33
3 m 25
4 f 28
And I want to query for a user id, and get back joined info from both tables for all users that share a relationship with user1.
assume that the first table has something like alter table thatFirstTable add unique index(userFromId, userToId) so there won't be any duplicates - each relationship between the two ids will be unique.
it doesn't matter who's the "from" or "to"
so the desired result would be something like this, if queried for relationships with user id: 1
userId moreInfo someInfo addlInfo
2 cat f 33
3 dog m 25
4 bear f 28
Thanks.
/EDIT this "works" but I suspect there's a better way?
SELECT * FROM users JOIN friends ON friends.userFrom = users.id OR friends.userTo = users.id WHERE users.id != 1 AND friends.userFrom = 1 OR friends.userTo = 1
/EDIT2 - I updated the sample output to better reflect the goal
try this query::
select tbl2.userid,tbl1.moreinfo,
tbl2.someinfo,tbl2.addinfo
from tbl1 join tbl2
on (tbl1.usertoid = tbl2.userid and tbl1.userfromid = 1)
You should just join the tables with the query below.
select u.userId, f.moreInfo, u.someInfo, u.addlInfo
from users AS u INNER JOIN friends AS f ON u.userId = f.UserToId
where f.userFrom = 1
Try this. Tested and 100% working
select a.userToID, a.moreInfo, b.someInfo, b.addInfo from tbl1 a
left outer join
tbl2 b on a.userToID = b.userId
where a.userFromID = 1;

How to left join or inner join a table itself

I have this data in a table, for instance,
id name parent parent_id
1 add self 100
2 manage null 100
3 add 10 200
4 manage null 200
5 add 20 300
6 manage null 300
How can I left join or inner join this table itself so I get this result below?
id name parent
2 manage self
4 manage 10
6 manage 20
As you can I that I just want to query the row with the keyword of 'manage' but I want the column parent's data in add's row as the as in manage's row in the result.
Is it possible?
EDIT:
the simplified version of my actual table - system,
system_id parent_id type function_name name main_parent make_accessible sort
31 30 left main Main NULL 0 1
32 31 left page_main_add Add self 0 1
33 31 left page_main_manage Manage NULL 0 2
my actual query and it is quite messy already...
SELECT
a.system_id,
a.main_parent,
b.name,
b.make_accessible,
b.sort
FROM system AS a
INNER JOIN -- self --
(
SELECT system_id, name, make_accessible, sort
FROM system AS s2
LEFT JOIN -- search --
(
SELECT system_id AS parent_id
FROM system AS s1
WHERE s1.function_name = 'page'
) AS s1
ON s1.parent_id = s2.parent_id
WHERE s2.parent_id = s1.parent_id
AND s2.system_id != s1.parent_id
ORDER BY s2.sort ASC
) b
ON b.system_id = a.parent_id
WHERE a.function_name LIKE '%manage%'
ORDER BY b.sort ASC
result I get currently,
system_id main_parent name make_accessible sort
33 NULL Main 0 1
but I am after this,
system_id main_parent name make_accessible sort
33 self Main 0 1
You just need to reference the table twice:
select t1.id, t1.name, t2.id, t2.name
from TableA t1
inner join TableA t2
on t1.parent_id = t2.Id
Replace inner with left join if you want to see roots in the list.
UPDATE:
I misread your question. It seems to me that you always have two rows, manage one and add one. To get to "Add" from manage:
select system.*, (select parent
from system s2
where s2.parent_id = system.parent_id
and s2.name = 'add')
AS parent
from system
where name = 'manage'
Or, you might split the table into two derived tables and join them by parent_id:
select *
from system
inner join
(
select * from system where name = 'add'
) s2
on system.parent_id = s2.parent_id
where system.name = 'manage'
This will allow you to use all the columns from s2.
Your data does not abide to a child-parent hierarchical structure. For example, your column parent holds the value 10, which is not the value of any id, so a child-parent association is not possible.
In other words, there's nothing that relates the record 2,manage,null to the record 1,add,self, or the record 4,manage,null to 3,add,10, as you intend to do in your query.
To represent hierarchical data, you usually need a table that has a foreign key referencing it's own primary key. So your column parent must reference the column id, then you can express a child-parent relationship between manage and add. Currently, that's not possible.
UPDATED: Joining by parent_id, try:
select m.id, m.name, a.parent
from myTable m
join myTable a on m.parent_id = a.parent_id and a.name = 'add'
where m.name = 'manage'
Change the inner join to a left join if there may not be a corresponding add row.