selecting n-m columns

Hi;
Have a very strange query
I have a table with n columns named say a1,a2,a3,…,an
Now I need to only retrieve the values of 1st m columns where m<=n
So generally I would write

select a1,a2,a3,...,am from table

But this gets tooooooooooooo tedious,is there any way like

select (*-3) from table

where i only require the n-3 columns data from the table
Thanks in advance

Okay, I think I know what you’re trying to do.

You could try something like this (not tested)

$sql = "SELECT ";

for($count = 0, $num_cols = 4; $count < $num_cols; $count++)
{
  $sql .= " a$count";
  
  if($count + 1 != $num_cols)
  {
  	$sql .=", ";
  }
}

$sql .= " FROM table";

echo $sql;

Someone else may have a better solution. Hope this helps though.

A friend of mine sent me this link.

http://www.postgresonline.com/journal/i … table.html

-boobay

If the number of fields is changing or you don’t know how many , you can use the mysql_num_fields http://us2.php.net/manual/en/function.m … fields.php to find out how many fields you need.

// Run a simple query to get all fields but LIMIT it to only one record
$result = mysql_query("SELECT * FROM table LIMIT 1");
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}

//  Get the data and put it into a variable for later use
$fieldCound = mysql_num_fields($result);

$sql = "Select ";

// In this FOR clause you can set the middle condition
// to $i < $fieldCount -3 Or whatever works
for ($i = 0; $i < $fieldCount; $i++) {

    $sql .= "a".$i.", ";
}
$sql .= "FROM table WHERE conditions = values";

Hope this helps.

Why don’t you just select on * instead of having to figure out which columns you want to select? You don’t -have- to use the selected columns.

Sponsor our Newsletter | Privacy Policy | Terms of Service