Select by latest date - php

I need to select statements where is fixed post id, group by user id and with latest date. Here is what i have:
$bids = "SELECT uid, Max(date_made), bid FROM ".$wpdb->prefix."auction_bids WHERE pid=$pid GROUP BY uid";
In this query is problem only with date, it returns first results, but i need last.
Here is the screen of my database:

You need to obtain the groupwise maximum:
SELECT uid, date_made, bid
FROM ${wpdb->prefix}auction_bids NATURAL JOIN (
SELECT uid, MAX(date_made) AS date_made
FROM ${wpdb->prefix}auction_bids
WHERE pid = $pid
GROUP BY uid
) AS t
WHERE pid = $pid
See it on sqlfiddle.

use min instead of max and grab the id, then join:
$bids = "SELECT ss.uid, ss.min, b.bid FROM ".$wpdb->prefix."auction_bids bid INNER JOIN (SELECT uid, MIN(date_made) as min FROM ".$wpdb->prefix."auction_bids WHERE pid=$pid GROUP BY uid) ss ON ss.uid = bid.uid";
It's not clear what you want from your English. Sorry.

Try this
"SELECT pre.uid, pre.date_made, pre.bid
FROM ".$wpdb->prefix." AS pre
WHERE pre.pid = $pid AND date_made =
(SELECT MAX(pre2.date_made) FROM ".$wpdb->prefix." AS pre2
WHERE pre2.uid = pre.uid)
GROUP BY pre.uid";
A bit complicated but efficient. Similar to eggyal's answer but I'm using theta style coding and hence easy to understand.

Related

I want the highest value to be on the top of the list

So I have this query and display the value, the 'time' is integer, it is often updated by clicking and when it is updated I want the highest value si on the top of the list when page is refresh, but it's not, I wonder if the grouping affects the query?
$sql= "select * FROM message
where userid_to = '$UserLoggedIn' || userid_from = '$UserLoggedIn'
group by conversation_id
ORDER BY time DESC";
I think you should be doing the aggregation on conversations inside a subquery to find the most recent time for each conversation. Then join back to your message table to obtain the full message record. I'm not sure what went wrong with your ordering, but your current query is not deterministic.
SELECT m1.*
FROM message m1
INNER JOIN
(
SELECT conversation_id, MAX(time) AS max_time
FROM message
WHERE userid_to = '$UserLoggedIn' OR userid_from = '$UserLoggedIn'
GROUP BY conversation_id
) m2
ON m1.conversation_id = m2.conversation_id AND
m1.time = m2.max_time
ORDER BY
m1.time DESC;
I would try doing it this way:
SELECT *, MAX(time) as time
FROM message
WHERE userid_to = '$UserLoggedIn' OR userid_from = '$UserLoggedIn'
GROUP BY conversation_id;

Multiple PHP subqueries not giving desired result

I have a MySQL table from which I want to extract attendance information(Student Id, course/subject for attendance, date range,whether the student was present or not). I have written the following query:
SELECT
COUNT(a_id),
(
SELECT COUNT(*) FROM attendance
WHERE state = 'present'
AND `dater` BETWEEN '$a' AND '$b'
) AS Count,
stud_id
FROM attendance
WHERE
stud_id =(SELECT id FROM users WHERE NAME = '$stud')
Which is giving me the correct results, but when I change the student,its not giving me the correct count for the days recorded for present. Not mention that I have not yet added the course parameter into the query
The MySQL table is as follows:
I need help for the query to return the desired results(Count the accurate days present for each student, as well as adding the course parameter into the query so that the query will look for attendance records for a specific course, for a specific student, for a specified date range).
Looks like you want to seperate your queries:
Select (select count(*) from <database>.attendance where state = 'present' AND (dater between '$a' and '$b') AND name=(SELECT id FROM users WHERE NAME = '$stud')) as present, (select count(*) from <database>.attendance where state = 'absent' AND (dater between '$a' and '$b') AND name=(SELECT id FROM users WHERE NAME = '$stud')) as absent from <database>.attendance WHERE stud_id =(SELECT id FROM users WHERE NAME = '$stud');
try this :)
Resolved it using JOIN as follows:
SELECT u.id, a.stud_id, a.course_id, count(*) FROM attendance a
JOIN users u ON u.id=a.stud_id
JOIN courses c ON c.c_id=a.course_id
WHERE a.state='present' and dater between '2017-09-01' and '2017-09-14'
GROUP BY a.stud_id, a.course_id;
Thanks for your help.

Pulling latest post from table

All,
I am trying to display the latest post from my authors.
The posts are in one table, the author in another. The queries used were: join on a column called content_id, and I am trying to work with MAX(item_date) which is the date the post was published.
Here are some queries I am running and the output, I seem to be getting everything except the latest posts from all authors:
First (and this bit is working) we need to get information about the author:
$query="SELECT content_id, title, source_image, url FROM content_detail where approved='y'";
$result1 = $mysqli->query($query) or die($mysqli->error.__LINE__);
// GOING THROUGH THE DATA
if($result1->num_rows > 0) {
while($fetch=mysqli_fetch_array($result1)) {
$title=$fetch['title'];
$feed_rss=$fetch['url'];
$content_id=$fetch['content_id'];
$source_image=$fetch['source_image'];
Now on that basis lets get the posts, round 1:
$query2 = "SELECT item_id, item_title, MAX(item_date) as item_date from posts WHERE content_id='$content_id' GROUP BY content_id";
$result2 = $mysqli->query($query2) or die($mysqli->error.__LINE__);
if($result2->num_rows > 0) {
while($rows2=mysqli_fetch_array($result2)) {
$item_id = $rows2['item_id'];
$item_title = $rows2['item_title'];
$item_date = $rows2['item_date']; `
This pulls back an in interesting set of results, the latest date of a post from an author, but not the latest title!
I have tried GROUP BY item_title and content_id to no avail.
The following pulls back just records that have more than one date in the database, the problem is (as this is new) some authors only have one post, these are not being displayed:
$query2 = "SELECT item_id, item_title, item_date FROM posts AS a WHERE content_id = content_id AND item_date = (
SELECT MAX(item_date)
FROM rssingest AS b
)
";
I have tried:
ORDER BY DATE DESC LIMIT 1
at the end of my queries to no avail.
item_date is a DATE type in the table.
Any help would be greatly appreciated!
Thanks,
You are running this query to get the maximum date:
SELECT item_id, item_title, MAX(item_date) as item_date
from posts
WHERE content_id = '$content_id'
GROUP BY content_id;
Of course you don't get the right item_title. It is not mentioned in the group by clause and has no aggregation function. So, you are using a MySQL extension (this query would fail in other databases).
You can get the most recent title using the substring_index()/group_concat() trick:
SELECT max(item_id),
substring_index(group_concat(item_title separator '|' order by item_date desc), '|', 1) as last_title,
MAX(item_date) as item_date
from posts
WHERE content_id = '$content_id'
GROUP BY content_id;
This will return one row. But, if there is only one row that you want, you can do:
SELECT p.*
from posts p
WHERE p.content_id = '$content_id'
ORDER BY item_date desc
LIMIT 1;
The previous version will generalize if you add a group by statement.
You need to join your posts table with itself to grab only the newest post for each content_id (which I believe is the author).
$query2 = "SELECT posts.item_id, posts.item_title, posts.item_date from posts
join (select max(item_id) max_id, content_id from posts group by content_id) maxid
on maxid.content_id=posts.content_id and maxid.max_id=posts.item_id
WHERE content_id='$content_id' ";
This opens the door for further optimization. You could grab the authors and their last post in one run.
SELECT content_detail.content_id,
content_detail.title,
content_detail.source_image,
content_detail.url ,
posts.item_id,
posts.item_title,
posts.item_date
FROM content_detail
join posts on content_detail.content_id=posts.content_id
join (select max(item_id) max_id, content_id from posts group by content_id) maxid
on maxid.content_id=posts.content_id and maxid.max_id=posts.item_id
where content_detail.approved='y'
But this could be an overstatement. You should of course try it yourself :)

How to select first in such sql code?

I have such sql:
mysql_query("SELECT *
FROM car
LEFT JOIN client
ON car.CodeClient = client.Code
LEFT JOIN telephone
ON car.CodeClient = telephone.CodeClient
WHERE Marka Like '$Marka'
and Model Like '%$Model%'
and EngineVol Like '%$EngineVol%'
and EngineType Like '%$EngineType%'
and DateMade Like '%$DateMade%'
");
And I need to select CodeClient and TelephoneNumber from telephone table, but select first entry for every Client, not all telephone, but first. Grouping is not the solving!
wouldn't this work? Sorry if it's not what you're looking for, but the question is a little unclear:
ORDER BY car.id LIMIT 1
or just:
LIMIT 1

How to write mysql5 query for finding duplicate rows from a table?

Hi I have a table like this
ID UserName
1 test#test.com
2 test#test.com
3 john#stack.com
4 test#test.com
5 adam#stack.com
6 john#stack.com
I need an output like this. I need only repeated rows list. How can I create this kind of an output using mysql query.
ID UserName Count
1 test#test.com 3
2 john#stack.com 2
Please help me.
Thanks.
I had the same problem some time ago and solved it like this (as far as I remember):
SELECT *
FROM tableA INNER JOIN
(SELECT DISTINCT MAX(id) as id, type_id, temp FROM tableA GROUP BY type_id, temp) AS t
ON tableA.id = t.id
AND tableA.type_id = t.type_id
AND tableA.temp = t.temp
You join the table with itself selecting the ids that are duplicate. The fields that should be tested against duplicate values are in this case type_id and temp. If you need more or less fields that should be considered as duplicates you can adjust the fields.
I don't know if this helps in your case and if it can be done in a more simple way, so I'm prepared for downvotes ;-)
Edit: removed last condition AND tableA.id < t.id as suggested by ypercube because it leads to 0 results.
It looks like you're trying to pull the following data:
First ID for a given UserName
The UserName itself
The total number of IDs for that UserName
This query should do the trick:
SELECT
MIN(id),
UserName,
COUNT(id)
FROM users
GROUP BY UserName;
since the ID is not unique so its a bit not logical to get the sum of unique UserName from the table.
If the ID is not required we can get the result from single query.
SELECT UserName, COUNT(UserName) AS Count
FROM TableName GROUP BY UserName
HAVING COUNT(UserName) > 1;
But in the case of ID in the result it will be a more complicated query including sub-query and inner table.
SELECT UserName
, COUNT(*) AS `Count`
FROM tableX
GROUP BY UserName
HAVING COUNT(*) > 1
Hi this is the right answer.
SELECT UserName, COUNT(UserName) AS Count
FROM TableName GROUP BY UserName
HAVING COUNT(UserName) > 1;

Categories