开发者

Selecting two rows from same table with condition

开发者 https://www.devze.com 2023-02-27 12:03 出处:网络
I am given a task to fetch two rows from the mysql table named as food. Now, I have a carbon_footprint column containing carbon footprints of all the foods. I have to now select two rows randomly fr

I am given a task to fetch two rows from the mysql table named as food.

Now, I have a carbon_footprint column containing carbon footprints of all the foods. I have to now select two rows randomly from the mysql table, but with one condition.

The two values should have a percentage difference of carbon footprint greater of equal to 70%.

The best I could do now is :

Select a.* from foods a CROSS JOIN foods b on ((a.co2 - b.co2)/b.co2) >= 0.7 ORDER BY RAND() LIMIT 2

But somehow, I am not getting the corr开发者_StackOverflowect answer. I know I am missing something really stupid.

Please help!


I tested the Function belows with the following values in a db Table:

Selecting two rows from same table with condition

Running the Inner query without the LIMIT or the ROUND() Brings back.

SELECT
              FoodName1 = A.FoodName
            , Food1Co2 = A.co2
            , FoodName2 = B.FoodName
            , Food2Co2 = B.co2
            , Number = ABS(((A.co2 - B.co2)/(A.co2)))
      FROM TB as A 
      CROSS JOIN TB B

Selecting two rows from same table with condition

Finally query all up is:

SELECT * , ABS(((tt.Food1Co2 - tt.Food2Co2)/(tt.Food1Co2)))
FROM (
    Select
              FoodName1 = A.FoodName
            , Food1Co2 = A.co2
            , FoodName2 = B.FoodName
            , Food2Co2 = B.co2
            , Number = ABS(((A.co2 - B.co2)/(A.co2)))
      FROM TB as A 
      CROSS JOIN TB B 
) tt
WHERE ABS(((tt.Food1Co2 - tt.Food2Co2)/(tt.Food1Co2))) >= 0.7
ORDER BY RAND() LIMIT 2

Notice how i added ABS() in to your function because your query will have negatives showing, so you need to remove the negatives and turn everything to a positive, and then do RAND() LIMIT. Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消