Jump to content

Recommended Posts

Hello

Is it any way possible to use if's in a query?

example:

SELECT `f`.`status AS `status`, `u`.`name` FROM `friends` AS `f`, `users` AS `user` WHERE (`f`.`id` = 1 OR `f`.`id2` = 1) AND `u`.`id` = `f`.`id`

 

What i want is to have "`u`.`id` = `f`.`id` or `id2`, and the id field from friends should be picked where the id field is not like 1.

In php I would have done it like this if it's not possible in sql:

<?php
$sql = mysql_query("SELECT `id`, `id2`, `status` FROM `friends` AS `f` WHERE `id` = 1 OR `id2` = 1");

while($row = mysql_fetch_array($sql)) {
  if($row['id'] == 1)
    $sql2 = mysql_query("SELECT * FROM `users` WHERE `id` = ". $row['id2']);
  else 
    $sql2 = mysql_query("SELECT * FROM `users` WHERE `id` = ". $row['id']);
  echo mysql_result($sql2, 0, 'name')
}
?>

But this solution would take to much resources. So any other solution?

 

Solution: http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_if

Link to comment
https://forums.phpfreaks.com/topic/83724-solved-if-in-query/
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.