Query two tables ORDER BY date - php

So I have two tables that displays values like a Facebook look-a-like feed. They both have a datetime column named date, but I want them to order them together by date DESC.
I think join is the correct way(?), but not quite sure. Can someone help me out?
Currently I have them in two different queries:
$status1 = "1";
$stmt1 = $link->prepare('
SELECT id
, ident_1
, ident_2
, date
, ident_1_points
, ident_2_points
FROM duel
WHERE active=?
ORDER
BY date
');
$stmt1-> bind_param('s', $status1);
and
$status2 = "OK";
$stmt2 = $link->prepare('SELECT id, ident, pp, date FROM sales WHERE status=? AND team IN (2, 3) ORDER BY date DESC LIMIT 20');
$stmt2->bind_param('s', $status2);
How should I do this?

If you want one continuous list containing data from both tables, and the whole thing ordered by date overall, then you might need a UNION query in a subquery, and then order the outer query, something like this:
SELECT *
FROM
(
SELECT id, ident_1, ident_2, date, ident_1_points, ident_2_points
FROM duel
WHERE active=?
UNION ALL
SELECT id, ident, pp, date, NULL, NULL
FROM sales
WHERE status=?
AND team IN (2, 3)
LIMIT 20
) list
ORDER BY date DESC
The requirement isn't 100% clear to be honest from your description (sample data and expected results always helps when asking SQL questions), but I think this is pretty close to what you need.
JOIN doesn't seem appropriate, unless you want a result set where items from each table are linked to each other by some common field, and you combine them such that you get all the columns side by side, showing the data from one table next to the data which matches from the other table.
If you're unsure, I suggest looking at tutorials / examples / documentation which show what JOIN does, and what UNION does.

Related

Select SQL query from two different tables but same database

i would like to select an sql query from two different tables. but both tables are in the same database.
this is my sql code and "air, temp, humidity, mq2" are from one table known as the "pi_sensors_network" while "Dust" is from another table known as "pi_dust_sensor". may i know how to go about selecting air, temp, humidity, mq2, Dust from 2 different tables but the same database? Thanks!
on a side note, there is no relation between both the tables. i just want to fetch the data from two different tables.
$sql = "SELECT air, temp, humidity, mq2, Dust FROM pi_sensors_network ORDER BY time DESC LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
Just use an alias for each table:
SELECT t1.air, t1.temp, t1.humidity, t1.mq2, t1.Dust As Dust1, t2.Dust As Dust2
FROM pi_sensors_network t1,
pi_dust_sensor t2
ORDER BY time DESC LIMIT 1";
You left a few things out in your schema description and query. Do you have a field in one of the tables that refers to the equivalent record in the other table (i.e. a foreign key)? If so, you can use a JOIN. You didn't mention which table has the time field.
Here is my stab at your desired query, but making assumptions on the unanswered questions. I assumed that you had a field pi_sensors_network.id that is a primary key for the pi_sensors_network table. I also assumed that there was a field pi_dust_sensor.fkid that connected the rows in the pi_dust_sensor table with the rows in the pi_sensors_network table.
SELECT air, temp, humidity, mq2, Dust
FROM pi_sensors_network INNER JOIN
pi_dust_sensor ON pi_sensors_network.id = pi_dust_sensor.fkid
ORDER BY time DESC LIMIT 1
Hopefully that will point you in the right direction. If you can answer my questions, I will be happy to update my answer.
you can combine data of two table in one object and can use after that how you want the output look like:
SELECT *
(
SELECT air, temp, humidity, mq2, '' As Dust,[time]
FROM pi_sensors_network
union all
select '' as air, '' as temp, '' as humidity, '' as mq2, Dust As Dust,[time]
from pi_dust_sensor
)base
ORDER BY [TIME] DESC

Pulling Last Two Dates PHP/MySQL

I have a table in my database which is updated randomly. I'm trying to pull entries by the latest date. This part is simply and I can do it with ease. However, I want to pull the two latest dates.
Example; If my last update was 2015-06-22 and the one before than was 2015-06-12 and the one before then was 2015-06-02. I would want to pull 2015-06-22 and 2015-06-15.
I would use a LIMIT 2, however, there are an unknown amount of items that may have the same date attached.
I haven't tried anything other than the LIMIT 2. After some research, I wasn't able to find anything to reference.
Update
I used SELECT DISTINCT to get the desired results.
SELECT DISTINCT dates FROM table ORDER BY dates DESC LIMIT 2
Will give you the latest 2 dates in the table.
I would have a column set to id, that is auto incremented, and do my query like this:
SELECT * FROM tbl_name ORDER BY `id` DESC LIMIT 2
Crap McAdam you beat me to it!
You can get the latest two dates using LIMIT, like you mentioned:
SELECT latestDates
FROM myTable
ORDER BY dateColumn DESC
LIMIT 2;
And you can join that to your original table to only select rows that occur on those two dates:
SELECT m.*
FROM myTable m
JOIN(
SELECT latestDates
FROM myTable
ORDER BY dateColumn DESC
LIMIT 2) tmp ON tmp.latestDates = m.dateColumn;

How to optimize a SQL query using multiple tables

I have this SQL query here that grabs the 5 latest news posts. I want to make it so it also grabs the total likes and total news comments in the same query. But the query I made seems to be a little slow when working with large amounts of data so I am trying to see if I can find a better solution. Here it is below:
SELECT *,
`id` as `newscode`,
(SELECT COUNT(*) FROM `likes` WHERE `type`="newspost" AND `code`=`newscode`) as `total_likes`,
(SELECT COUNT(*) FROM `news_comments` WHERE `post_id`=`newscode`) as `total_comments`
FROM `news` ORDER BY `id` DESC LIMIT 5
Here is a SQLFiddle as well: http://sqlfiddle.com/#!2/d3ecbf/1
I would recommend adding a total_likes and total_comments fields to the news table which gets incremented/decremented whenever a like and/or comment is added or removed.
Your likes and news_comments tables should be used for historical purposes only.
This strenuous counting should not be performed every time a page is loaded because that is a complete waste of resources.
You could rewrite this using joins, MySQL has known issues with subqueries, especially when dealing with large data sets:
SELECT n.*,
`id` as `newscode`,
COALESCE(l.TotalLikes, 0) AS `total_likes`,
COALESCE(c.TotalComments, 0) AS `total_comments`
FROM `news` n
LEFT JOIN
( SELECT Code, COUNT(*) AS TotalLikes
FROM `likes`
WHERE `type` = "newspost"
GROUP BY Code
) AS l
ON l.`code` = n.`id`
LEFT JOIN
( SELECT post_id, COUNT(*) AS TotalComments
FROM `news_comments`
GROUP BY post_id
) AS c
ON c.`post_id` = n.`id`
ORDER BY n.`id` DESC LIMIT 5;
The reason is that when you use a join as above, MySQL will materialise the results of the subquery when it is first needed, e.g at the start of this query, mySQL will put the results of:
SELECT post_id, COUNT(*) AS TotalComments
FROM `news_comments`
GROUP BY post_id
into an in memory table and hash post_id for faster lookups. Then for each row in news it only has to look up TotalComments from this hashed table, when you use a correlated subquery it will execute the query once for each row in news, which when news is large will result in a large number of executions. If the initial result set is small you may not see a performance benefit and it may be worse.
Examples on SQL Fiddle
Finally, you may want to index the relevant fields in news_comments and likes. For this particular query I think the following indexes will help:
CREATE INDEX IX_Likes_Code_Type ON Likes (Code, Type);
CREATE INDEX IX_newcomments_post_id ON news_comments (post_id);
Although you may need to split the first index into two:
CREATE INDEX IX_Likes_Code ON Likes (Code);
CREATE INDEX IX_Likes_Type ON Likes (Type);
First check for helping indexes on columns id, post_id and type,code.
I assume this is T-SQL, as that is what I am most familiar with.
First I would check indexes. If that looks good, then I'd check statement. Take a look at your query map to see how it's populating your result.
SQL works backward, so it starts with your last AND statement and goes from there. It'll group them all by code, and then type, and finally give you a count.
Right now, you're grabbing everything with certain codes, regardless of date. When you stated that you want the latest, I assume there is a date column somewhere.
In order to speed things up, add another AND to your WHERE and account for the date. Either last 24 hours, last week, whatever.

Combine multiple unique MySQL tables and order by one column

I've been trying to accomplish this MySQL query for the past few days now with very little luck. I'd like to combine these multiple tables and their columns, then order by one that they have in common (not by name, but by content). I have the following database tables:
mb_bans:
mb_ban_records:
mb_kicks:
mb_mutes:
mb_mutes_records:
mb_warnings:
What I'm trying to accomplish is something among the lines of this:
Unfortunately I am beyond stumped on how to combine these MySQL tables together but also at the same time keeping them in separate categories - ordered by the _time columns in each table. How would I approach this? I have been unsuccessful with my attempts at retrieving them.. The closest I could get was combining just the _time columns of each, then giving it a value in the query as "date", however I cannot do much with the results. I would still need to call it as the individual rows, correct? I could probably use fetchAll but then I would be unable to add anything to the values..
$banq = $db->prepare('SELECT banned, banned_by, ban_reason, ban_time, ban_expires_on FROM '.BAN_TABLE.' ORDER BY ban_time DESC');
$kickq = $db->prepare('SELECT kicked, kicked_by, kick_reason, kick_time FROM '.KICK_TABLE.' ORDER BY kick_time DESC');
$muteq = $db->prepare('SELECT muted, muted_by, mute_reason, mute_time, mute_expires_on FROM '.MUTE_TABLE.' ORDER BY mute_time DESC');
$warnq = $db->prepare('SELECT warned, warned_by, warn_reason, warn_time FROM '.WARN_TABLE.' ORDER BY warn_time DESC');
$banq->execute();
$kickq->execute();
$muteq->execute();
$warnq->execute();
Essentially I'd like to combine all of those queries together as one + the two _record tables. Any advice that could help me is greatly appreciated as I've spent countless hours trying to figure this out on my own.
Thanks in advance!
Try this:
SELECT * from (
SELECT banned as Punisher, banned_by as Punished, ban_reason as Reason, ban_expires_on as Expire, ban_time as Date FROM mb_bans
UNION
SELECT kicked as Punisher, kicked_by as Punished, kick_reason as Reason, NULL as Expire, kick_time as Date FROM mb_kicks
UNION
SELECT muted as Punisher, muted_by as Punished, mute_reason as Reason, mute_expires_on as Expire, mute_time as Date FROM mb_mutes
UNION
SELECT warned as Punisher, warned_by as Punished, warn_reason as Reason, NULL as Expire, warn_time as Date FROM mb_warnings
) d order by d.Date DESC;
EDIT
how could I get the type of record? (IE. whether the returned result is from the bans table, mutes table, kicks table etc.)
SELECT * from (
SELECT banned as Punisher, banned_by as Punished, ban_reason as Reason, ban_expires_on as Expire, 'ban' as TableType, ban_time as Date FROM mb_bans
UNION
SELECT kicked as Punisher, kicked_by as Punished, kick_reason as Reason, NULL as Expire, 'kick' as TableType, kick_time as Date FROM mb_kicks
UNION
SELECT muted as Punisher, muted_by as Punished, mute_reason as Reason, mute_expires_on as Expire, 'mute' as TableType, mute_time as Date FROM mb_mutes
UNION
SELECT warned as Punisher, warned_by as Punished, warn_reason as Reason, NULL as Expire, 'warn' as TableType, warn_time as Date FROM mb_warnings
) d order by d.Date DESC;
The generic answer for this question is,
SELECT A.COL, B. COL, C.COL
FROM TABLE1 AS 'A'
INNER JOIN TABLE2 AS 'B' WHERE A.ID = B.ID
INNER JOIN TABLE3 AS 'C' WHERE B.ID = C.ID
.
.
.
<YOU CAN PUT AS MUCH AS JOINS YOU WANT>
ORDER BY <REQUIRED_COL>
Now, do this in your huge scenario.

Mysql - How to get a row number after Order by?

Let's say I have a table with the following columns:
p_id
userid
points
Let's say these columns have over 5000 records. So we actually have users with points. Each user has an unique row for their point record. Imagine that every user can get points on the website by clicking somewhere. When they click I update the database with the points they get.
So we have a table with over 5000 records of people who have points, right? Now I would like to order them by their points (descending), so the user with the most point will be at the top of the page if I run a MySQL query.
I could do that by simply running a query like this:
SELECT `p_id` FROM `point_table` ORDER BY `points` DESC
This query would give me all the records in a descending order by points.
Okay, here my problem comes, now (when it is ordered) I would like to display each user which place are they actually. So I'd like to give each user something like this: "You are 623 of 5374 users". The problem is that I cannot specify that "623" number.
I would like to run a query which is order the table by points it should "search" or count the row number, where their records are and than return that value to me.
Can anyone help me how to build a query for this? It would be a really big help. Thank you.
This answer should work for you:
SET #rank=0;
SELECT #rank:=#rank+1 AS rank, p_id FROM point_table ORDER BY points DESC;
Update: You might also want to consider to calculate the rank when updating the points and saving it to an additional column in the same table. That way you can also select a single user and know his rank. It depends on your use cases what makes more sense and performs better.
Update: The final solution we worked out in the comments looked like this:
SELECT
rank, p_id
FROM
(SELECT
#rank:=#rank+1 AS rank, p_id, userid
FROM
point_table, (SELECT #rank := 0) r
ORDER BY points DESC
) t
WHERE userid = intval($sessionuserid);
Row number after order by
SELECT ( #rank:=#rank + 1) AS rank, m.* from
(
SELECT a.p_id, a.userid
FROM (SELECT #rank := 0) r, point_table a
ORDER BY a.points DESC
) m
For some reason the accepted answer doesn't work for me properly - it completely ignores "ORDER BY" statement, sorting by id (primary key)
What I did instead is:
SET #rn=0;
CREATE TEMPORARY TABLE tmp SELECT * FROM point_table ORDER BY points DESC;
SELECT #rn:=#rn+1 AS rank, tmp.* FROM tmp;
Add a new column for position to the table. Run a cron job regularly which gets all the table rows ordered by points and then update the table with the positions in a while loop.

Categories