2

I have code in PHP and i want it to make only sql like

table content

word   size place
small  10   home
large  18   outside
dog    11   home
cat    6    home
dog    20   outside
small  99   outside

The PHP code isnt absolutly correct, but you will see what i need.

$input = array("small", "dog");
$place2 = array();
$sql1 = SELECT word,size,place FROM TAB WHERE word = input[0];
$sql2 = SELECT word,size,place FROM TAB WHERE word = input[1];

if ((($sql1['size'] - $sql2['size']) == 1) && ($sql1['place'] == $sql2['place']) ) {
   $place2[] = $sql2['place'].$sql2['word'].$sql1['word'];
}

and output $place2[] like a result of query

Is it possible to make this purely in sql without using PHP code? I mean just make some query (Tquery) that will compare values from two different queries and output array of place and word values that will accept that if statement? i need that because db is faster than php and i have a lot of rows

3
  • PHP is going to execute faster than SQL afaik. Commented Feb 15, 2012 at 22:22
  • crush is correct. For straight selects mysql will generally be faster, but when you start needing calculated conditions, you'll often find that PHP performs better. Commented Feb 15, 2012 at 22:26
  • are you using mysql or sql server or something else? a stored procedure would be a good way to achieve this Commented Feb 15, 2012 at 22:29

1 Answer 1

2

PHP would probably be faster/more efficient, but if you really want a query to do it:

SELECT CONCAT(`b`.`place`, `b`.`word`, `a`.`word`) AS `output`
FROM `tab` `a`
JOIN `tab` `b` ON `b`.`word`='dog'
WHERE `a`.`word`='small'
   AND `a`.`size`-`b`.`size` = 1
   AND `a`.`place`=`b`.`place`

As I said, though, the PHP version is probably far more efficient.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.