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

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. :)

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

@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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.