简体   繁体   中英

how to build a dynamic runtime query in mysql php?

I do not know how to classify this question. Vaguely, its about using calculated value in the WHERE clause of a mysql query performed using a php script.

Here's the scenario - I've a mysql table with structure like this: table_id[int], item_id[int], item_rating[int] Now the item_rating column can have either a "1" or a "0" value in it. The table_id column is set to auto_increment and the item_id column can have duplicate values also.

So a typical table will look like below -

table_id item_id item_rating
1           item1     1
2           item5     0
3           item1     1
4           item1     1
5           item5     1
6           item1     0

What i intend to do i for each item_id, i count the number of item_rating = 1 and item_rating = 0 and then take the difference of item_rating values to get the final rating for that item (final_item_rating = item_rating(with value=1) - item_rating(with value=0) ).

Now the issue: I have a php script that takes values from these tables, and then displays the item details ordered on the "final_item_rating" value - something like: select * from table_name order by final_item_rating desc

only problem is, since this final_item_rating is not a column in itself, and is actually based on run time value of the query, how do i build a query?

hope i have the question clear :)

This query may help you:

SELECT sum(item_rating) AS SumRatings
FROM table_name
WHERE item_rating=1
GROUP BY item_id
ORDER BY SumRatings; 

This query would sum the ratings, and order the result with the highest rating on top:

select  item_id
,       sum(case when item_rating = 1 then 1 else -1 end) as rating
from    YourTable
group by
        item_id
order by
        sum(case when item_rating = 1 then 1 else -1 end) desc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM