mysql查询:如何通过该计数加入和计算重复项和顺序

时间:2014-08-13 19:45:55

标签: php mysql join count duplicates

我有两张桌子。 'table_a'有更多列需要连接到一个结果:

'table_a' (time, col_1, col_2,....col_50) //'col_[1-50]' columns contains '$id'

example col_1 values: (1000, 1000, 1000, 2000, 2000, 2000)
example col_2 values: (2000, 2000, 1000, 2000, 3000, 3000) //etc

'table_b' ($id, name) //contains 'name' acording to '$id' from 'table_a'

example id,name values: (1000, John), (2000, Peter), (3000, Annie) //etc

我需要一些复杂的查询,就像我试着为你写的一样(我知道,有趣的方式):

SELECT and JOIN or UNION col_[1-50] from table_a AS some 'result row'
AND count(*) duplicates/occurrences AS 'count', (DISTINCT after that)
(then GET 'name' FROM 'table_b' according to '$id') 
and ORDER BY that 'count'

最终查询结果应该是:

echo $query['count']." - ".$query['name']." - ".$query['id']."<br>";

6 - Peter - 2000
4 - John - 1000
2 - Annie - 3000

谢谢你们,我迷路了....

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

  SELECT tb.name, 
         SUM(
           (tb.id = ta.col_1),
           (tb.id = ta.col_2),
           ...
           (tb.id = ta.col_50)
         ) count, 
         tb.id
    FROM table_a ta
    JOIN table_b tb
  /*  ON tb.id IN (
           ta.col_1,
           ta.col_2,
           ... 
           ta.col_50
         ) /* Not strictly necessary, but may help performance */
GROUP BY tb.id, tb.name

我建议您的数据结构可以改进。我个人会将table_a存储为两列,property_idperson_id,并将每个当前行分为50行。它会使这样的查询变得更加简单。