Mysql joining two tables - mysql

I need to join the following two tables
table_A
id userId name score game
1 2343 me 45 Palo Alto
2 6575 other 21 SF
3 6575 other 2 miami
table_B
id userId pen mango
1 2343 3 4
2 2343 5 7
3 6575 1 2
Here is the join:
SELECT COUNT(a.userId), SUM(b.pen), SUM(b.mango)
FROM table_A AS a
LEFT JOIN table_B b ON a.userId = b.userId
WHERE userId = 2343;
The problem is I am getting count(userId) equals to 2, but I need it to be 1. What am I doing wrong?

Change it to the following:
count(distinct a.userId)

Your query will gerneate two rows, each row corresponding to one row in table_B (one for id 1, one for id 2).
I am not sure why you think the resulting count(a.userId) should be 1, but you could enforce this by using a GROUP BY clause à la GROUP BY b.userId.

I am confused about what you are doing. You can still get SUM of Pen and Mango without joining the two tables. And another thing, why do you still use the COUNT function where, in fact, you know that you are querying to ONLY ONE ID? Right?
SELECT SUM(Pen) as TotalPen,
SUM(Mango) as TotalMango
FROM table_B
WHERE userId = 2343
But if you want a joined tables you could write something like this:
SELECT SUM(COALESCE(b.pen,0)) as TotalPen,
SUM(COALESCE(b.mango,0)) as TotalMango
FROM table_A AS a LEFT JOIN table_B b ON a.userId = b.userId
WHERE a.userId = 2343;
The problem is I am getting count(userId) equals to 2, but I need it to be 1. - The query is correct but your understanding is wrong. Obviously there are two record IDs of 2343 in Table_B

Related

Mysql Query with two seperate join

Does anyone know the solution to this problem ?
There are 3 Tables: orders, order_groups and stores.
I want to list the orders, with the names of the stores where the order was placed, and where the order is going to be delivered.
I keep the from_store_id, and to_store_id in the order_groups table
Listing these orders would be simple, i just left join the order_groups to orders, and select the name, from_shop_id and to_shop_id, but the problem is i want the name of the stores not the id, and the store names are placed in a different table (stores)
Here is what im talking about:
Table orders
id group_id name madeup_id
1 11 johnny cash 1
2 12 billy bob 1
LEFT JOIN order_groups on order_groups.id = orders.group_id
Table order_groups
id from_store_id to_store_id
11 55 56
12 56 55
Table stores
id store_name
55 thisstore
56 thatstore
The result im looking for is:
name from_store to_store
1.johhny cash thisstore, thatstore
2.billy bob thatstore, thisstore
The statement i have yet:
SELECT
orders.name, something as from_store, something as to_store
FROM orders
LEFT JOIN order_groups on order_groups.id = orders.group_id
somehow join stores on the order_groups.from_store_id = stores.id
WHERE orders.madeup_id = 1
Any idea how to select and join the store names to the query ?
One more question. I actually want to list two kind of orders in one query from different tables too, im on the right track with this structure ?
SELECT a,b FROM a LEFT JOIN b ON b.something=a.something WHERE something
UNION ALL
SELECT a,b FROM c LEFT JOIN c ON c.something=a.something WHERE something
You only need to join 2 times the same table!
SELECT
orders.name, fromStore.store_name as from_store, toStore.store_name as to_store
FROM orders
LEFT JOIN order_groups on order_groups.id = orders.group_id
left join stores fromStore on the order_groups.from_store_id = fromStore.id
left join stores toStore on the order_groups.to_store_id = toStore.id
WHERE orders.madeup_id = 1

mysql triple join query

I have tables shown below:
users table
user_id user_email user_name
1 a#a.com a
2 b#b.com b
3 c#c.com c
bookmarks table
bookmark_id user_id bookmark_url
1 1 http://aaa.com
2 3 http://bbb.com
3 3 http://ccc.com
4 3 http://ddd.com
comments table
comment_id user_id content
1 2 'hello'
2 2 'hello2'
What I want to get is like this :
user_id user_email user_name bookmarksCount commentsCount
1 a#a.com a 1 0
2 b#b.com b 0 2
3 c#c.com c 3 0
From above, each xxx_id is auto incremented sequence id.
I think to get above result, I have to join these 3 tables.But, if there is no match user_id in bookmarks and comments table, they can't be joined. But I have to get result with 0 if there is no match.
Is it possible to join these tables to get result even though there is no match column?
You can just use correlated subqueries:
select u.*,
(select count(*) from bookmarks bm where bm.user_id = u.user_id
) as cnt_bookmarks,
(select count(*) from comments c where c.user_id = u.user_id
) as cnt_comments
from users u;
If you attempt to do this using join, you will have problems, because you will generate a Cartesian product of bookmarks and comments for each user. In addition, doing the aggregation after the join is likely to incur performance problems, because the data for the aggregation will be larger than necessary.
For this query, indexes on bookmarks(user_id) and comments(user_id) should provide very good performance.

Select rows with Left Outer Join and condition - MySQL

PEOPLE PEOPLE_FAVS
id user_id fav_id
------ ------- ----------
1 1 1
2 1 2
3 1 5
4 2 1
5 2 2
6
I have two tables PEOPLE and PEOPLE_FAVS, I am trying to get all PEOPLE which have not favorited number '5' so it should return
PEOPLE
id
------
2
3
4
5
6
I'm trying with this query:
SELECT `people`.`id`
FROM `people`
LEFT OUTER JOIN `people_favs` ON (`people_favs`.`user_id` = `people`.`id`)
WHERE (`people_favs`.`fav_id` != 5)
GROUP BY `people`.`id`
Here is a SQL Fiddle: http://sqlfiddle.com/#!2/4102b8/3
SELECT p.*
FROM people p
LEFT
JOIN people_favs pf
ON pf.user_id = p.id
AND pf.fav_id = 5
WHERE pf.fav_id IS NULL
http://sqlfiddle.com/#!2/665b6/1
You don't actually need to use an outer join. Outer joins are often used when you want to see ALL rows from one table, regardless of their condition with another. While it would work in this case (as seen by Strawberry's example), you can use the NOT EXISTS operator to check for ids that do not have 5 as a favorite.
As far as I am aware, there is little to no performance difference, but this query is a little shorter. I also feel it is a little more logical, because you aren't really joining information. That's just a personal opinion/thought though.
Try this:
SELECT id
FROM people
WHERE NOT EXISTS(SELECT id FROM people_favs WHERE fav_id = 5 AND user_id = id);
SQLFiddle example using your data.
Did you try to simply do this:
SELECT DISTINCT `people`.`id`
FROM `people`
JOIN `people_favs` ON (`people_favs`.`user_id` = `people`.`id`)
WHERE (`people_favs`.`fav_id` <> 5)
GROUP BY `people`.`id`

Mysql Table Structure Working Fast?

I am planning to create a website similar to IMDB.com. To reduce execution time I am using the following structure. Is it okay for faster working?
Table - 1
Id Movie_name description
1 name one some description
2 name two some description
3 name three some description
Table 2
id actorname
1 name 1
2 name 2
3 name 3
4 name 4
Table 3
id movieid actorid
1 1 1
2 1 2
3 1 3
4 1 9
5 2 6
6 2 5
7 2 8
8 2 1
When I want to list actors in a movie program will retrieve actors ids from table 3 and find respective names from table 2 (using single query). When I want to list the movies of a actor it will retrieve movie ids from table 3 and find respective names from first table. Will it work properly? Any other ideas?
This will give all actors in a specified movie,
SELECT c.ID, c.actorName
FROM table1 a
INNER JOIN table3 b
ON a.ID = b.movieID
INNER JOIN table2 c
ON b.actorid = c.ID
WHERE a.ID = 1
This one will give all movies for a specified actor
SELECT a.*
FROM table1 a
INNER JOIN table3 b
ON a.ID = b.movieID
INNER JOIN table2 c
ON b.actorid = c.ID
WHERE c.ID = 1
SQLFiddle Demo (both queries)
To further gain more knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins
UPDATE 1
This is called Relational Division
SELECT a.ID, a.Movie_Name
FROM table1 a
INNER JOIN table3 b
ON a.ID = b.movieID
INNER JOIN table2 c
ON b.actorid = c.ID
WHERE c.ID IN (1, 2, 3)
GROUP BY a.ID, a.Movie_Name
HAVING COUNT(DISTINCT c.ID) = 3
SQL of Relational Division
I suggest that you modify table3 by taking away the id field. Use the movieid and actorid together as your primary key. You might want to add other fields to this table such as name of character and order of appearance as suggested in the comment by Jermaine Xu.

Getting value of Mapping table IDs when value is from same column

Im really struggling to get my head around what should be simple,
I have two tables, one contains records the other is a mapping table.
records
ID Title Description
1 record 1 desc 1
2 record 2 desc 2
3 record 3 desc 3
4 record 4 desc 4
mapping table
ID1 ID2
1 3
2 4
What I want to do is get the two titles of each row in the mapping table. So the above would output
record 1 record 3
record 2 record 4
Im missing something really obvious, trying multiple joins results in errors trying to link the same table twice.
The following returns NUll
SELECT records.title FROM mapping
LEFT JOIN records
ON mapping.ID1 = records.id
AND mapping.ID2 = records.id
try this one: (UNTESTED)
SELECT b.Title as TitleA,
c.Title as TitleB
FROM mapping a
INNER JOIN records b
on a.ID1 = b.ID
INNER JOIN records c
on a.ID2 = c.ID