PHP MySQL newest records from multiple tables - php

I'm trying to select the latest 10 records from multiple tables (ORDER BY date). For example, 8 of the newest records might be in one table and 2 in another (10 rows in total). Is there a way to select those 10 records?

SELECT *
FROM
( SELECT * FROM x
UNION ALL
SELECT * FROM y
) n
ORDER
BY date DESC
LIMIT 10;

You can maybe use:
SELECT column_name(s)
FROM table1
ORDER BY date LIMIT 0,8
UNION ALL
SELECT column_name(s)
FROM table2
ORDER BY date LIMIT 0,2;

SELECT * FROM (
SELECT some_data AS alias1, date_field AS mydate
FROM table1
UNION ALL
SELECT datazzz AS alias1, another_datefield AS mydate
FROM table2
)
ORDER BY mydate DESC LIMIT 10
Syntax might need a little bit of tweaking, but that's the gist of it.
Specifically, you need to select whatever data you want out of each of the tables and then use aliases to make sure they have the same column names (otherwise they can't be returned in the same result set). Then after that you need to order by the common date field.

Related

PHP - Select random row from table

My table has around 10k rows. How can I query select 1 random row of the last 10 added rows? I have a date column that is datetime of when the row was added.
This is one I use to get the last 10 rows:
SELECT id FROM mytable order by date desc LIMIT 10
I know I can do SELECT id FROM mytable ORDER BY RAND() LIMIT 1 but that just choose any random row, not from the last 10 rows.
One method uses a subquery:
SELECT t.*
FROM (SELECT id
FROM mytable
ORDER BY date DESC
LIMIT 10
) t
ORDER BY rand()
LIMIT 1;
This version uses the syntax conventions for MySQL.
You can use select * in the subquery to fetch the whole row.

MySQL ORDER BY "count(*) and 2 other parameters" from another table

I have been struggling with this problem for about month..
Have been searching and reading many posts, but still can't figure out, how to make this work..
Basically: I got 2 database tables fun_posts and fun_post_upvotes And I want to
SELECT *
FROM fun_posts
ORDER BY (HOTTEST POSTS(MOST UPVOTED THIS WEEK))
This is my latest code, that won't work
SELECT *
FROM fun_posts
ORDER BY (SELECT count(*), image_id, date
FROM fun_post_upvotes
GROUP BY image_id
ORDER BY DATE(date) > (NOW() - INTERVAL 7 DAY) DESC,
count(*) DESC,
date DESC)
If I divide this line into 2 different SELECT functions, they work. I can select simple posts and I can select upvotes count ordered like I want.
But If I make them into one line like that, I get following error:
#1241 - Operand should contain 1 column(s)
EDIT NR 1:
fun_posts table
fun_post_upvotes table
Problem with Answer that I checked:
Here, look how posts are ordered in my select function. (It selects like I want) 10->134->132->2->13
And here with given code (It selects image, but not in that order) 10->122->39->8->110
You can use a join to do this
SELECT fp.*, fpu.`cnt`
FROM fun_posts fp
LEFT JOIN ( SELECT image_id, COUNT(*) AS cnt
FROM fun_post_upvotes
WHERE `date` > (NOW() - INTERVAL 7 day)
GROUP BY image_id
) fpu ON ( fpu.image_id = fp.id )
ORDER BY fpu.cnt DESC, fp.`date` DESC, fp.`id` DESC;
It selects a list from fun_post_upvotes grouped by image_id and counts the amount of rows. That list is returned to the main query and matches (LEFT JOIN) on fp.id. The query will first show the item with the most upvotes in the past 7 days, than the least. If no upvotes are found, the result will still return them, but at the bottom in no specific order.
You can edit the order by, to obtain the items in the order you like.
Here a sqlfiddle.com

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;

Using order by DESC or ASC in mysql queries with UNION keyword

In my page I used the following query for displaying choices starts from current time to old time of choices. But it selects the row starts from old time choices to current time choices.
I want to display the choices starts from current time to old one
$result=mysql_query("(SELECT choice_id,poll_id,choicecreationtime from je_addchoice ORDER BY choicecreationtime DESC)
UNION
(SELECT choice_id,poll_id,datetime_voted from je_user_vote ORDER BY datetime_voted DESC)");
I dont know why this problem occurs. If I don't use the UNION means it works fine. For example. The below query shows the order of current time to old
$result = mysql_query("SELECT * FROM je_addchoice, je_addpoll where je_addpoll.privacy='0' AND je_addpoll.start_date <= '$check_date' AND je_addpoll.end_date >='$check_date' AND je_addpoll.poll_id=je_addchoice.poll_id order by je_addchoice.choicecreationtime desc");
Anybody can help me to solve this problem
wrap the unioned queries by subquery and order them on the outer query
SELECT *
FROM
(
SELECT choice_id, poll_id, choicecreationtime AS TIME
FROM je_addchoice
UNION
SELECT choice_id, poll_id, datetime_voted AS TIME
FROM je_user_vote
) s
ORDER BY TIME DESC
UPDATE 1
SELECT choice_id, poll_id, choicecreationtime AS TIME
FROM je_addchoice
UNION
SELECT choice_id, poll_id, datetime_voted AS TIME
FROM je_user_vote
ORDER BY Time DESC
As documented under UNION Syntax:
To apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the SELECT:
(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);
However, use of ORDER BY for individual SELECT statements implies nothing about the order in which the rows appear in the final result because UNION by default produces an unordered set of rows. Therefore, the use of ORDER BY in this context is typically in conjunction with LIMIT, so that it is used to determine the subset of the selected rows to retrieve for the SELECT, even though it does not necessarily affect the order of those rows in the final UNION result. If ORDER BY appears without LIMIT in a SELECT, it is optimized away because it will have no effect anyway.
To use an ORDER BY or LIMIT clause to sort or limit the entire UNION result, parenthesize the individual SELECT statements and place the ORDER BY or LIMIT after the last one. The following example uses both clauses:
(SELECT a FROM t1 WHERE a=10 AND B=1)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2)
ORDER BY a LIMIT 10;
A statement without parentheses is equivalent to one parenthesized as just shown.
Try this:
SELECT choice_id, poll_id, dt
FROM (SELECT choice_id, poll_id, choicecreationtime dt FROM je_addchoice
UNION
SELECT choice_id, poll_id, datetime_voted dt FROM je_user_vote ) AS A
ORDER BY dt DESC

How to structure this SQL query?

So basically I'm getting notifications of new content on my website. I have 4 tables -
articles
media
updates
comments
Each table has a set of its own columns (I can include these if anyone wants). There is one distinct column every table has, this is the timestamp column (a big int formatted column with data from the PHP time() function). My solution to getting the last 30 modifications is to select the first 30 rows from these 4 tables ordered by timestamp descending.
Here is the query I have so far, it doesn't work and I'm wondering if someone could help me. -
SELECT * FROM `articles`
UNION SELECT * FROM `media`
UNION SELECT * FROM `updates`
UNION SELECT * FROM `comments`
ORDER BY `timestamp` DESC
LIMIT 30
EDIT:
I was also using another query before -
SELECT * FROM `articles` ,`media` ,`updates` ,`comments`
ORDER BY `timestamp` DESC
LIMIT 30
and kept getting this error -
Column 'timestamp' in order clause is ambiguous
EDIT 2
I realise now I have to use the AS clause in my statement to combine these results into one table.
SELECT a.*,m.*,u.*,c.* from articles AS a
LEFT JOIN media AS m ON (m.timestamp = a.timestamp)
LEFT JOIN updates AS u ON (u.timestamp = a.timestamp)
LEFT JOIN comments AS c ON (c.timestamp = a.timestamp)
ORDER BY timestamp desc LIMIT 30
Your union can work, but only if you can create some sort of common field list. For example, lets say you have a description field in each table, with different names. Something like this will work...
SELECT TimeStamp,'Articles',Art_desc AS Description FROM articles
UNION ALL
SELECT TimeStamp,'Media',Media_Desc FROM Media
UNION ALL
SELECT TimeStamp,'Updates',Update_Desc FROM Updates
UNION ALL
SELECT TimeStamp,'Comments',Comment FROM Comments
ORDER BY timeStamp DESC LIMIT 30
In essence, you are creating result sets of 3 consistent columns, so UNION will work in this case.

Categories