Jump to content

A little mySQL hustle here, cant figure something out!!!


npsari

Recommended Posts

 

Hi there,

 

I have table called Info.

 

There are two main colombs (Name, News)

 

I try display each distinct Name and his latest News:

 

$q = "SELECT DISTINCT Name FROM
info
ORDER BY Date ASC, Time ASC
LIMIT 10;";

$res = @mysql_query($q);

while($r = @mysql_fetch_array($res))
{	
print "$r[Name]";
print "$r[News]";
}

 

But the "News" dont show in Results!

 

I want the latest News of a Distinct Name to show too

 

What should i add to mySQL code guys

Link to comment
Share on other sites

Why can't you just do this:

 

<?php

$conn = mysql_connect("localhost", "user", "pass") or die(mysql_error());

$q = mysql_query("SELECT * FROM info ORDER BY Date ASC, Time ASC LIMIT 10;") or die(mysql_error());

while($r = mysql_fetch_array($q)) {
echo $r['Name']."\n\n";
echo $r['News']."\n\n";
}

?>

 

I always find it easier to select * and just fish out what you need. :)

Link to comment
Share on other sites

Oh, sorry, I used the GROUP BY now

 

$q = "SELECT DISTINCT(Name), News FROM
info
GROUP BY Name
ORDER BY Date DESC, Time DESC
LIMIT 4;";

 

It arranges all Names DESC

 

But it doesnt show the latest News of the person DESC

It shows his First News

Link to comment
Share on other sites

@chigley

 

I always find it easier to select * and just fish out what you need. :)

 

For easier, read "lazier".

 

The query is less efficient, retrieving unnecessary data. And from a maintenance viewpoint when you or someone else reads it later, you cannot easily tell what the query is really for.

 

@npsari

 

SELECT n.name, n.news

FROM news n

INNER JOIN (SELECT id, MAX(CONCAT(date,time))as latest) as a

ON n.id = a.id AND CONCAT(n.date,n.time) = a.latest

Link to comment
Share on other sites

Sorry, my wife was nagging to go shopping and I forgot the FROM and GROUP BY in my haste

 

SELECT n.name, n.news

FROM news n

INNER JOIN (SELECT name, MAX(CONCAT(date,time)) as latest FROM news GROUP BY name) as a

ON n.name = a.name AND CONCAT(n.date,n.time) = a.latest

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.