Extracting from multiple tables by id and ordering by created date - php

I`m trying to extract the activity of a user with a single query. I need to do it with one single query so I can use zend paginator.
I have 5 tables: users, replies, threads, wiki_articles and wiki_article_revisions. Each table has 2 common columns created_by and created_on.
I've tried using left join but I think what it returns is not correct and I'm unable to order all activity by created_on
Here is the join I've tried:
SELECT * FROM `users` u
LEFT join `replies` r ON u.id = r.created_by
LEFT join `threads` t ON u.id = t.created_by
LEFT join `wiki_articles` wa ON u.id = wa.created_by
LEFT join `wiki_article_revisions` war ON u.id = war.created_by
WHERE (u.`name` = 'CGeorges')

My thought process was wrong. I should have used UNION for this, like:
(SELECT id, name, created_on FROM users WHERE id = 1)
UNION
(SELECT id, name, created_on FROM threads WHERE created_by = 1)
UNION
(SELECT id, content, created_on FROM replies WHERE created_by = 1)
UNION
(SELECT id, title, created_on FROM wiki_articles WHERE created_by = 1)
ORDER by created_on DESC

Related

EXISTS query optimization on mysql query

I have a big data problem with MySQL.
I have:
a users table with 59033 rows, and
a user_notes table with 8753 rows.
But when I search which users have user note in some dates.
My query like this :
SELECT u.*, rep.name as rep_name FROM users as u
LEFT JOIN users as rep on rep.id = u.add_user
LEFT JOIN authorization on authorization.id = u.authorization
LEFT JOIN user_situation_list on user_situation_list.user_situation_id = u.user_situation
WHERE
EXISTS(
select * from user_notes
where user_notes.note_user_id = u.id AND user_notes.create_date
BETWEEN "2017-10-20" AND "2017-10-22"
)
ORDER BY u.lp_modify_date DESC, u.id DESC
Turn it around -- find the ids first; deal with the joins later.
SELECT u.*,
( SELECT rep.name
FROM users AS rep
WHERE rep.id = u.add_user ) AS rep_name
FROM (
SELECT DISTINCT note_user_id
FROM user_notes
WHERE create_date >= "2017-10-20"
AND create_date < "2017-10-20" + INTERVAL 3 DAY
) AS un
JOIN users AS u ON u.id = un.note_user_id
ORDER BY lp_modify_date DESC, id DESC
Notes
No GROUP BY needed;
2 tables seem to be unused; I removed them;
I changed the date range;
User notes needs INDEX(create_date, note_user_id);
Notice how I turned a LEFT JOIN into a subquery in the SELECT list.
If there can be multiple rep_names, then the original query is "wrong" in that the GROUP BY will pick a random name. My Answer can be 'fixed' by changing rep.name to one of these:
MAX(rep.name) -- deliver only one; arbitrarily the max
GROUP_CONCAT(rep.name) -- deliver a commalist of names
Rewriting your query to use a JOIN rather than an EXISTS check in the where should speed it up. If you then group the results by the user.id it should give you the same result:
SELECT u.*, rep.name as rep_name FROM users as u
LEFT JOIN users as rep on rep.id = u.add_user
LEFT JOIN authorization on authorization.id = u.authorization
LEFT JOIN user_situation_list on user_situation_list.user_situation_id = u.user_situation
JOIN user_notes AS un
ON un.note_user_id
AND un.create_date BETWEEN "2017-10-20" AND "2017-10-22"
GROUP BY u.id
ORDER BY u.lp_modify_date DESC, u.id DESC

Multiple Counts in MYSQL PHP Query

I'm trying to create a leaderboard but i'm not sure how to do the mysql query.
I would like to count all the levels from a player in the skills table and get the total Level and count all the experience from a player in the experience table and get the Total Exp along with displaying the persons name from the users column.
There is 3 tables factions_mcmmo_users, factions_mcmmo_experience, factions_mcmmo_skills.
This is what i have so far but it doesn't work:
$sql = ("SELECT a.id,
(SELECT COUNT(*) FROM factions_mcmmo_experience WHERE user_id = a.id) as TotalXP,
(SELECT COUNT(*) FROM factions_mcmmo_skills WHERE user_id = a.id) as TotalLevel
FROM (SELECT DISTINCT id FROM factions_mcmmo_users) a LIMIT 10;");
Any help would be very appreciated
EDIT: I have it working now but i'm unsure if its the most efficient way to do things so if anyone could help me out if theres a better way, it would mean a lot.
I would also like to know if it's possible to display the total exp and level with commas if the number is in the thousands for example: total level 5,882 and total xp 582,882
EDIT 2:
I have figured out how to format the numbers but still don't know if my code is efficient
$sql = ("SELECT id, user,
(SELECT FORMAT(Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy),0) FROM factions_mcmmo_skills b WHERE b.user_id = a.id) as TotalLevel,
(SELECT FORMAT(Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy),0) FROM factions_mcmmo_experience c WHERE c.user_id = a.id) as TotalXP
FROM (SELECT id, user FROM factions_mcmmo_users) a group by id ORDER BY TotalLevel DESC, TotalXP DESC LIMIT 10;");
EDIT 3
Updated code from scaisEdge but was displaying everyones level as 1 and XP as 1, so i changed count(*) changed to sum, added an order By TotalLevel in Descending order and that seems to have worked but i can't get it to display the persons name (user column) in the user table? not sure if i was supposed to change to sum because it didn't work the other way.
$sql = ("SELECT a.id, b.TotalXP, c.TotalLevel
FROM (SELECT DISTINCT id FROM factions_mcmmo_users) a
INNER JOIN (
SELECT user_id, Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy) as TotalXP
FROM factions_mcmmo_experience
GROUP By user_id
) b on b.user_id = a.id
INNER JOIN (
SELECT user_id, Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy) as TotalLevel
FROM factions_mcmmo_skills
GROUP by user_id
) c on c.user_id = a.id
ORDER BY TotalLevel DESC
LIMIT 10;");
EDIT 4
Everything working but when i try to format the totals using "FORMAT(Sum(Columns), 0) on the inner joins, the EXP Total appears to work but the main Total Level is not displaying results that are over 1,000 and it breaks the leaderboard positioning, it should be sorting them on total level but it appears to be random, when u remove the format,0 it goes back to working
I would like it to display commas if the number number is the thousands for example: Total Level: 5,532 and Total EXP 5882,882
See live demo: http://mcbuffalo.com/playground/leaderboards/server/factions-mcmmo.php
Updated Code trying to use Format:
$sql = ("SELECT a.id, a.user, b.TotalXP, c.TotalLevel
FROM (SELECT id, user FROM factions_mcmmo_users) a
INNER JOIN (
SELECT user_id, FORMAT(Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy), 0) as TotalXP
FROM factions_mcmmo_experience
GROUP By user_id
) b on b.user_id = a.id
INNER JOIN (
SELECT user_id, FORMAT(Sum(taming)+Sum(mining)+Sum(woodcutting)+Sum(repair)+Sum(unarmed)+Sum(herbalism)+Sum(excavation)+Sum(archery)+Sum(swords)+Sum(axes)+Sum(acrobatics)+Sum(fishing)+Sum(alchemy), 0) as TotalLevel
FROM factions_mcmmo_skills
GROUP by user_id
) c on c.user_id = a.id
ORDER BY TotalLevel DESC;");
EDIT 5
Changed number with PHP, everything works
Original Images
you could use an couple of inner join
$sql = ("SELECT a.id, a.name, b.TotalXP, c.TotalLevel
FROM (SELECT DISTINCT id, name FROM factions_mcmmo_users) a
INNER JOIN (
SELECT user_id, COUNT(*) as TotalXP
FROM factions_mcmmo_experience
GROUP By user_id
) b on b.user_id = a.id
INNER JOIN (
SELECT user_id, COUNT(*) as TotalLevel
FROM factions_mcmmo_skills
GROUP by user_id
) c on c.user_id = a.id
LIMIT 10

mysql activity feed of people you follow (likes, comments, etc.)

Some background:
I'm developing kind of social network.
There is DB with next tables:
users(user_id, user_name, password, etc.)
posts(post_id, user_id, post_text, post_data, etc.)
followings(relationship_id, follower_id, following_id, added_date_time)
likes(like_id, user_id, post_id, added_date_time)
comments(comment_id, user_id, post_id, comment_text, added_date_time)
The question is:
How can I implement query which would fetch information about what my followings(people I follow) have did recently (e.g. someone liked/commented something) and order this array of info by date_time?
Can I make it using one query? Or I'll have to make multiple queries and handle all this stuff in PHP by myself?
What is the best approach?
You can normalize the output in a select union like this one
SELECT t.type, t.user_id, u.user_name, t.type_id, t.post_id, t.text, t.added_date_time
FROM (
SELECT 'posts' as type, p.user_id, p.post_id as type_id, p.post_id, post_text as text, p.added_date_time
FROM posts p
JOIN followings f ON (f.following_id = p.user_id)
WHERE f.follower_id = #user
UNION
SELECT 'comments' as type, c.user_id, c.comment_id as type_id, c.post_id, comment_text as text, c.added_date_time
FROM comments c
JOIN followings f ON (f.following.id = c.user_id)
WHERE f.follower_id = #user
UNION
SELECT 'likes' as type, l.user_id, l.like_id as type_id, l.post_id, post_text as text, l.added_date_time
FROM likes l
JOIN followings f ON (f.following.id = c.user_id)
JOIN posts p ON (l.post_id = p.post_id)
WHERE f.follower_id = #user
) as t
JOIN users u ON (t.user_id = u.user_id)
ORDER BY added_date_time DESC;
So you can get all the data in only one query.
I hope it works fine for you.
You have to seperate at least the queries for likes and comments, since the result set is different.
Otherwise your query would look e.g. like:
SELECT comment_id,comment_text,added_date_time FROM comments WHERE user_id IN (SELECT following_id FROM followings WHERE follower_id={{USER_ID_FROM_USER}}) ORDER BY added_date_time
This will get you the comments from people which are followed by {{USER_ID_FROM_USER}} ordered by date.

Select a row from two tables depend on primary key(Mysql)?

I have two table users and album. In users table there is user_id primary key .In other table albums there are multiple rows with that user_id because every time when a user upload a new album it uploads with user_id as foreign key. I want to select only once the user_id with other table(album) ignore other result set.
How can I achieve this?
SELECT a.*, b.*
FROM users a
INNER JOIN album b
ON a.user_ID = b.user_ID
INNER JOIN
(
SELECT user_ID, MAX(photo_id) max_rec
FROM album
GROUP BY user_ID
) c ON b.user_ID = c.user_ID AND
b.photo_id = c.max_rec
SELECT album.* FROM album LEFT JOIN users ON user.id = album.id WHERE user.id = SOMEIDHERE
I believe this will work, your not giving me a whole lot of info to work with.
SELECT *
FROM ( SELECT u.*, a.*
FROM users AS u
INNER JOIN album AS a
ON u.user_ID = a.user_ID
ORDER BY a.created DESC) AS h
GROUP BY user_ID
ORDER BY b.created DESC -> ORDER BY whatever row you wish for. In this case the newest one is chosen.

Select and count distinct active users by platform and compare if they exist in other tables

I have about six(6) tables each linked with userid. One of the tables is userinfo. The user info contains user details including their store platform(eg magento)
Userinfo contains both active and non-active users (active users have created at least one activity in the other 5 tables).
I want to count distinct number of users in the userinfo with platform of magento who have records in any of the other tables.
Currently I am able to count distinct number of users in the other five tables with the ff code but want to join this with the userinfo table so I can select active users with platform magento.
Without adding the userinfo table means I have no way of selecting users by platform.
Selecting users in userinfo table only, with platform of magento will be easy, but that means I may select users who only register but do not go on to create activity on my app.
$query3 = ("SELECT COUNT(*)
FROM (
SELECT userid FROM table1
UNION SELECT userid FROM table2
UNION SELECT userid FROM table3
UNION SELECT userid FROM table4
UNION SELECT userid FROM table5
) AS UserIDs");
$result3 = mysql_query($query3) or die(mysql_error());
$row3 = mysql_fetch_row($result3);
echo "Number of distinct users in all tables = ".$row3[0] ."<br />";
**Table 1**
Id userid name adresss
**Table 2**
Id Title Sex userid
**Table 3**
Id userid amount
**Table 4**
Id price promotion userid productid
**Table 5**
Id userid category tax weight
**userinfo**
Id userid username password platform
Expanding on the UNION subselect from my other suggestion, you can JOIN this with the UserInfo table and get your distinct count.
SELECT COUNT (DISTINCT ui.UserID))
FROM (
SELECT UserID FROM Table1
UNION SELECT UserID FROM Table2
UNION SELECT UserID FROM Table3
UNION SELECT UserID FROM Table4
UNION SELECT UserID FROM Table5
) AS id
INNER JOIN UserInfo ui ON ui.UserID = id.UserID
WHERE ui.Platform = 'Magento'
I would like that :
SELECT COUNT(DISTINCT ui.userid) as number
FROM userinfo ui
INNER JOIN table1 t1 ON (t1.userid = ui.userid)
INNER JOIN table2 t2 ON (t2.userid = ui.userid)
INNER JOIN table3 t3 ON (t3.userid = ui.userid)
INNER JOIN table4 t4 ON (t4.userid = ui.userid)
INNER JOIN table5 t5 ON (t5.userid = ui.userid)
WHERE ui.platform = 'magento'
And if you do :
SELECT COUNT(DISTINCT ui.userid) as number
FROM userinfo ui, table1 t1, table2 t2, table3 t3, table4 t4, table5 t5
WHERE ui.platform = 'magento'
AND t1.userid = ui.userid
AND t2.userid = ui.userid
AND t3.userid = ui.userid
AND t4.userid = ui.userid
AND t5.userid = ui.userid
If it doesn't work, try to replace SELECT COUNT(DISTINCT ui.userid) as number by SELECT ui.* for see.

Categories