ViperSBT Posted July 13, 2006 Share Posted July 13, 2006 I have two fields in a table that both may contain a userid. I would like to find the number of rows for each userid occurance, no matter which field it is in.... Something like:So if the two fields were user1 and user2 and the data looked like this:user1 user2 2 4 1 2 3 5 1 2I would want my result to be:1 = 2 Counts2 = 3 Counts3 = 1 Counts4 = 1 Counts5 = 1 Counts Quote Link to comment https://forums.phpfreaks.com/topic/14517-counting-from-two-fields/ Share on other sites More sharing options...
lead2gold Posted July 13, 2006 Share Posted July 13, 2006 try this:[code]SELECT (SELECT count( * )FROM tablenameWHERE userida = '1') AS user1, (SELECT count( * )FROM tablenameWHERE useridb = '1') AS user2[/code] Quote Link to comment https://forums.phpfreaks.com/topic/14517-counting-from-two-fields/#findComment-57492 Share on other sites More sharing options...
ViperSBT Posted July 13, 2006 Author Share Posted July 13, 2006 That would require that I provide the UserID to count for, I want it to return all UserIDs in the table. Also this provides two separate columns for each UserID, I need one column that is the UserID and another column that is the counts for the number of times that UserID exists in either of the fields of that table. Quote Link to comment https://forums.phpfreaks.com/topic/14517-counting-from-two-fields/#findComment-57513 Share on other sites More sharing options...
kenrbnsn Posted July 13, 2006 Share Posted July 13, 2006 Try this:[code]<?php$temp = array();$q = "select user1, user2 from tablename"$rs = mysql_query($q) or die("Problem with query: $q<br>" . mysql_error());while($rw = mysql_fetch_assoc($rs)) { $temp[] = $rw['user1']; $temp[] = $rw['user2'];}$nw = array_count_values($temp);echo '<pre>' . print_r($nw,true) . '</pre>';?>[/code]Ken Quote Link to comment https://forums.phpfreaks.com/topic/14517-counting-from-two-fields/#findComment-57525 Share on other sites More sharing options...
lead2gold Posted July 13, 2006 Share Posted July 13, 2006 my badtry this then[code]SELECT u.userid, (SELECT count( * )FROM tablenameWHERE userida = u.userid ) + (SELECT count( * )FROM tablenameWHERE useridb = u.userid ) AS countFROM usertable u[/code] Quote Link to comment https://forums.phpfreaks.com/topic/14517-counting-from-two-fields/#findComment-57527 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.