Retrieving data across two tables - mysql

I'm pretty new to MySQL and need to get data from a column where the id in another column of the same table matches the id in a second table and I'm not sure how to go about it.
I haven't tried anything yet as I'm too new to go about answering my own question, sorry.
So my first table looks like this
userid questionid score
-----------------------------
1 1 5
1 2 4
1 3 7
1 4 10
1 4 6
And my 2nd table looks like this
otherfields userid
---------------------
blah 1
blah 2 2
etc 3
you 4
get 5
the 6
idea 7
So what I need to do is select all the scores from table 1 where userid of table 1 matches the user id of table 2.

So you want to sum up the score for each user?
Then something like this could help:
SELECT t2.userid, t2.otherfields, SUM(t1.score) AS sum_score
FROM first_table t1
LEFT JOIN second_table t2 ON t1.userid = t2.userid
GROUP BY t2.userid
First, you join the two tables together based on userid which is the same over both tables. Then you GROUP all rows which belong to the same user (e.g. question 1-5 for user 1) together and finally you SUM up the scores of each row of a group.

Related

Get count of a column based on join from other table

I am new to SQL. I have to tables and trying to get the count of column from table 1 and join by other column in table 2.
Table 1:
credits | sec_code | student_acc_id
--------------------------------
4 TUB 2098
5 JIY 2099
6 THG 3011
Table 2:
id| sec_code | student_acc_id | stu_id
-------------------------------------
1 TUB 2098 1011
5 JIY 2099 1011
7 THG 3011 1012
I would like to get the sum of credits for the student by getting the stu_id from table2 from sec_code and get all the student_acc_id for stuId and sum the credits column in table1 for all the student account Ids found from table 2. I am not sure how can we join or make this query simple.
Normally my approach is to inlcude this two to three different SQL statements, but i am looking for this in a one sql query if possible.
For the above example lets say i want to get sum of credits for all student_acc_id where stu_id is 1011 from second table. i just have the first table. So the output should be 4+5 as both accounts belong to the same student.
So i need:
--> get the stu_id based on sec_code from table two (lets say for TUB sec_code)
--> get all student_acc_id from table where stu_id is result from above statement
-->now using those all student_acc_id's sum the credit in table 1
Any help is appreciated !
Use Join according to your Data exist.
But as per the sample data better to get Data from Right table.
select
tab2.stud_id,
SUM(tab1.credits) AS credit_sum
from
table1 as tab1
right join
table2 as tab2
on tab1.student_acc_id = tab2.student_acc_id
and tab1.sec_cd = tab2.sec_cd
where
tab2.stud_id in(
select distinct stud_id
from table2
where student_acc_id = '2098'
)
group by
tab2.stud_id;
You can check its sample output here. Please click for fiddle solution.
try like below
select t2.stu_id,
sum(t1.credits)
from t1 join t2 on t1.student_acc_id=t2.student_acc_id and
t1.sec_code=t2.sec_code
group by stu_id
Having count(stu_id)>1

Count rows in table with certain value in other table

I need a quick way to find the Number of items in a table. The items are linked to an other table. Table 1 is products and table 2 is orders.
Orders contains a paid status (1 or 0).
Orders table example:
id paid
1 0
2 1
Products table example:
id orderid type
1 1 5
2 1 5
3 1 3
4 2 5
5 2 5
6 2 3
Products contains a id (orderid) that refers to the order and a type. So i need the number of products where type = 5 and paid = 1 in the orders table.
What is the best and fastest way to archieve this?
So I need all the paid products with type 5. The result should be '2'.
you can use join like this,
SELECT COUNT(*) AS num_rows
FROM products
LEFT JOIN orders ON orders.id = products.orderid
WHERE type = 5 AND paid = 1
One way is to use a join statement. Making some assumptions about your schema, the following should work:
SELECT COUNT(p.`id`) FROM `products_table` p
LEFT JOIN `orders_table` o ON p.`orderid` = o.`id`
WHERE o.`paid` = 1
AND p.`type` = 5

Get Last row in each group and order whole array by ID(pk) DESC and join with other Table

I want the last row in each and every group(Group By user_id).
Structure of Table is like follows:
Table: user_messages
id(PK) | user_id(FK) | read_admin_status | created_at
1 5 0 date
2 5 0 date
3 5 0 date
4 5 1 date
5 6 1 date
6 6 1 date
7 7 0 date
8 7 0 date
Table: users
id | username
Now I want username from users tables and I want other details from user_messages.
Now I want data of user_id 5 and want it's last row only.
likewise for other groups I want last row of each group and from users table I want username by joining the tables.
Please help me out with this if you can. Thank you.
You might try something like this:
SELECT user_messages.id, users.username
FROM (
SELECT MAX(id) AS max_id
FROM user_messages
GROUP BY user_id
) AS ids
INNER JOIN user_messages ON ids.max_id = user_messages.id
INNER JOIN users ON user_messages.user_id = users.id
This query will choose the largest message ID in each user's group of messages, which is the same as getting the last ID when ordering by ID, and then use the associated user ID to get the username. I only selected the message ID and username, but you could get whatever information you wanted out of those tables.

Deleting cross referenced data

I have the following MySQL table:
id rid
----- ------
1 2
2 1
2 3
3 2
1 3
3 1
I want to change this so only one row per relation exists.
e.g:
id rid
----- ------
1 2
2 3
1 3
If you always have pairs (as in your example):
delete from table
where id > rid;
This keeps the record where id is smaller.
If there is the possibility that no all pairs exist, then:
delete t
from table t left outer join
(select least(id, rid) as lid, greatest(id, rid) as gid, count(*) as cnt
from table t2
group by least(id, rid), greatest(id, rid)
) t2
on least(t.id, t.rid) = t2.lid and greatest(t.id, t.rid) = gid
where id < rid or t2.cnt = 1;
EDIT (explanation):
How does the second query work? Let me be honest, what I want to write is this:
delete t from table t
where id < rid or
(id > rid and
not exists (select 1 from table t2 where t2.id = t.rid and t2.rid = t.id
);
That is, I want to keep all records where id < rid. But then, I also want to keep all singleton records where rid > id. I don't think MySQL allows the syntax with the where clause.
Instead, the query in the answer counts the number of times that a pair exists, by looking at the smallest value and the largest value. For the data in the question, the result of the subquery is:
id rid cnt
1 2 2
2 3 2
1 3 2
So, all of these would use the id < rid to select the row. If you had one more row, say 4, 1. It would look like:
lid gid cnt
1 2 2
2 3 2
1 3 2
1 4 1
In this case, the first three would take the row with id < rid. But the new row would also be selected because the cnt is 1.
If you had duplicates in the table and a primary key, there would be a slight variation on the query that would do the same thing.

MySQL 5.1.61 - Update table based on two seperate tables

I have three tables:
Table_1:
id name
1 NULL
2 OLED
3 legion
4 project100
5 group3
6 0
7 25
Table_2:
projectID externalID projectTypeID projectDescription
0 0 5 UNALLOCATED
25 220339 1 OLED
Table_3:
typeID typeDesc
1 Playbook Aligned
2 Transactional Project
3 External Programs
4 UPI
5 Unallocated
I am trying to update Table_1. I only want to update rows with a 'name' that is a digit. I know that I can select those by doing:
SELECT `name`
FROM `Table_1`
WHERE `name` REGEXP '^[0-9]*$'
This gives me:
name
0
25
What I want to do now is to update these Table_1 entries based on Table_2 and Table_3. I need to find the row in Table_2 where Table_2.projectID = Table_1.name. Then, I need to find the row in Table_3 where Table_3.typeID = Table_2.projectTypeID. Finally, I need to update Table_1.name with Table_3.typeDesc. It's a confusing situation - unfortunately I can't do much to change the way that these tables are set up. Any help is appreciated.
UPDATE
Table_1
JOIN Table_2 on(Table_2.projectID = Table_1.name)
JOIN Table_3 on(Table_3.typeID = Table_2.projectTypeID)
SET Table_1.name = Table_3.typeDesc
WHERE Table_1.name REGEXP '^[0-9]*$';