table design + SQL question

Posted by topdog 219 days ago Questions| weight null table All

I have a table foodbar, created with the following DDL. (I am using mySQL 5.1.x)

CREATE TABLE foodbar (
    id          INT NOT NULL AUTO_INCREMENT,
    user_id     INT NOT NULL,
    weight      double not null,
    created_at  date not null
);

I have four questions:

  1. How may I write a query that returns a result set that gives me the following information: user_id, weight_gain where weight_gain is the difference between a weight and a weight that was recorded 7 days ago.
  2. How may I write a query that will return the top N users with the biggest weight gain (again say over a week).? An 'obvious' way may be to use the query obtained in question 1 above as a subquery, but somehow picking the top N.
  3. Since in question 2 (and indeed question 1), I am searching the records in the table using a calculated field, indexing would be preferable to optimise the query - however since it is a calculated field, it is not clear which field to index (I'm guessing the 'weight' field is the one that needs indexing). Am I right in that assumption?.
  4. Assuming I had another field in the foodbar table (say 'height') and I wanted to select records from the table based on (say) the product (i.e. multiplication) of 'height' and 'weight' - would I be right in assuming again that I need to index 'height' and 'weight'?. Do I also need to create a composite key (say (height,weight)). If this question is not clear, I would be happy to clarify
Discuss Bury


Who Voted for this Question