Forum Moderators: coopster

Message Too Old, No Replies

MySQL query

where to start

         

WhosAWhata

1:51 am on Oct 26, 2004 (gmt 0)

10+ Year Member



Though i am getting quite fluent in PHP, i'm a beginner in the field of MySQL,

i need to do a few queries,
my table looks something like this


+----+--+---+
¦info¦ 1 ¦ 1 ¦
+----+--+---+
¦more¦ 1 ¦ 2 ¦
+----+--+---+
¦some¦ 1 ¦ 3 ¦
+----+--+---+
¦wow¦ 2 ¦ 1 ¦
+----+--+---+
¦yes ¦ 2 ¦ 2 ¦
+----+--+---+

i have one column that groups the data, and one that creates the seperate "call numbers" for that group.

i need to find the biggest value in the first column, then find the highest value in that group

i would appreciate code, but more than that, i would like a place to learn the structure of the queries, PHP.net is very unhelpful for that.

thanks

coopster

12:33 pm on Oct 26, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You mean you want to sort the columns in descending order?

SELECT * FROM table ORDER BY column2 DESC, column3 DESC;

You're right, you won't find much help on SQL on the PHP site. Better off trying the MySQL tutorial [dev.mysql.com] or search the net for "learn sql".

WhosAWhata

2:59 pm on Oct 26, 2004 (gmt 0)

10+ Year Member



the code you gave me just rearranged the table, how do i put the highest value of column 2 and the higest value of column 3 into variables
say
$col2 = highest from column 2
$col3 = highest from column 3 with that value of column 2

in the case i provided
$col2 = "2";
$col3 = "2";
even though column 3 has a 3 in it, that row has a lower value in column 2

coopster

4:21 pm on Oct 26, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Assign the query to a variable then use mysql_query() [php.net] to run the query, then use mysql_fetch_assoc() [php.net] to get the values from the result set.
$sql = "SELECT * FROM table ORDER BY column2 DESC, column3 DESC"; 
$rows = mysql_query($sql);
$row = mysql_fetch_assoc($rows);
$col2 = $row['column2'];
$col3 = $row['column3'];
print "$col2<br />";
print "$col2<br />";

WhosAWhata

5:14 pm on Oct 26, 2004 (gmt 0)

10+ Year Member



it works great! thanks a bunch coop!

one thing though,
how can i allow that if a user enters the address as page.php?col2=1

then it will find the biggest value for col3 with respect to that col2?

i took a stab in the dark by making it so that if a value is already present for col2 it will use this query instead
$sql = "SELECT * FROM table WHERE col2 IS $col2 ORDER BY col3 DESC";

it didn't work

coopster

6:55 pm on Oct 26, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Close, but you have to get the syntax right:
$sql = "SELECT * FROM table WHERE col2 = $col2 ORDER BY col3 DESC";

WhosAWhata

3:10 am on Oct 27, 2004 (gmt 0)

10+ Year Member



thanks, exactly what i needed, i'll look at some tutoruals when i get a chance