开发者

Mysql combine rows?

I have a table with itemid|fieldid|value and i'm trying to setup a query that will combine some data and return a mathc percentage along with the result. for example, some data could be

itemid  fieldid value  
19  193 1  
45  193 1  
37  201 6  
25  201 1  
45  201 6  
19  201 6  
19  201 5 

Now i want for example, to get all the rows with fieldid = 193 AND value = 1 as well as the rows with fieldid = 201 AND value = 6. The ideal result would be something like : itemid, percentage getting 100% for all itemids which match both conditions and 50% for all that match one. I have this query working for doing the above over multiple columns but it will not work here

select id,user_class,admin, ( 
if (admin = 1,1,0)+ 
if (user_class = 'SA',1,0)
)/2*100 as the_percent 
from users 
WHERE
admin = 1 OR user_class = 'P'
GROUP BY id
order by the_percent DESC

Also i got the following for absolute matching

SELECT开发者_如何学Python users.id FROM users WHERE
users.id IN 
(
SELECT DISTINCT itemid FROM extra_field_values 
INNER JOIN (SELECT DISTINCT itemid FROM extra_field_values WHERE fieldid = 201 AND value = 6 ) a1 USING (itemid)
INNER JOIN (SELECT DISTINCT itemid FROM extra_field_values WHERE fieldid = 193 AND value = 1 ) a2 USING (itemid)
)

but combining the two seems to be a bit of a puzzle to me


I think you might be able to make use of a UNION and selecting from a table subquery to make this happen. Perhaps something along the lines of:

SELECT itemid, count(*)/2*100 AS percent FROM
    ( SELECT itemid FROM extra_field_values WHERE fieldid = 201 AND value = 6
    UNION ALL
    SELECT itemid FROM extra_field_values WHERE fieldid = 193 AND value = 1 ) AS t
GROUP BY itemid;

It's been a while since I've done anything complex in mysql, and I threw this together in notepad so my syntax could be off :) But basically we create a view of the matching ids, then from that table create our statistics. (You'll also want to do some performance evaluation as well to see how it stacks up compared to doing multiple queries as well).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜