0

I'm currently in the process of learning MySQL, and I've come to learning variables, however I'm having an issue accessing whats saved in my variable; I'm getting my variable contains with the following command:

SELECT 
    @foods := `idFood`, `price`
from
    `foods`;

This seems to be working okay, and this is resulting a table, now I'm wanting to sort my table animals by the following command:

Select 
    *
From
    `Animals`
order by `Animals`.`Food consumption` * @foods.price
where @foods.idFood = `Animals`.`FoodType`

The Animals.FoodType is holding the id of the food, that the animal is consuming.

When running this, I'm getting an error in the last part, where I'm using the variable, I've been playing around with it for quite a while without any luck.

2
  • if you're getting an error, posting the error-message would be nice ;) Commented Aug 24, 2011 at 10:26
  • Simply an SQL syntax error that I can't debug Commented Aug 24, 2011 at 10:35

1 Answer 1

1

You should use one query with JOIN clause. Try this query -

SELECT a.* FROM animals a
LEFT JOIN foods f
  ON a.FoodType = f.idFood
ORDER BY a.`Food consumption` * f.price;

About the variables - variables in MySQL are scalar values, you cannot set an array into variable.

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

4 Comments

How does this function exactly, it selects an animal 'a', and a food 'f' and simply compare them?
The JOIN clause is used to extract data from two related tables. In your case tables are related by food id. To view full result set use 'SELECT * FROM ...' instead of 'SELECT a.* FROM...'.
Yea okay, I think I get it now, thanks, this actually just changed to way I work with SQL
@Skeen: I think you should try improving your SQL skills, avoiding variables until you hit problems that (MySQL) can't deal easily or efficiently without them.

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.