ORDER BY在另一个表中找到的大多数行

时间:2015-06-27 08:10:56

标签: php mysql

我有2个表,1个名为googleimage,1个名为googleimagefound,googleimagefound有数千行,每行有一个image_id列,对应于来自googleimage表(id)的各自图像,googleimage表中的每个图像都可能有数千个从googleimagefound表中对应的行。

我要做的是从googleimage表中选择所有图像,然后按照googleimagefound表中找到的行数对其进行排序。

实施例,

googleimage表有3行,ID为1,2,3

googleimagefound表有100行,其中50行有image_id 1,其中20个有image_id,其中30个有image_id 3

我想说

SELECT * FROM googleimage ORDER BY most rows found in googleimagefound table where id = googleimagefound.image_id

任何帮助都会受到欢迎

4 个答案:

答案 0 :(得分:0)

尝试这种方式:

SELECT g.*,T1.Found
FROM googleimage g JOIN
(SELECT image_id,COUNT(image_id) as Found
 FROM googleimagefound
 GROUP BY image_id) T1 ON g.image_id=T1.image_id
ORDER BY T1.Found DESC

结果将如下:

id     name    others     Found
--------------------------------
1      NameA   Value1     120
5      NameD   Value4     95
3      NameB   Value2     82

答案 1 :(得分:0)

你的意思是这样的:

SELECT count(distinct f.image_id) as mostrowsfound
, i.* FROM googleimage as i
 LEFT JOIN googleimagefound as f ON i.id = f.image_id
 GROUP BY i.id
 ORDER BY mostrowsfound DESC

答案 2 :(得分:0)

您可以加入来自googleimagefound的聚合查询,该查询计算每个ID的行数:

SELECT    g.*
FROM      googleimage g
LEFT JOIN (SELECT   image_id, COUNT(*) AS cnt
           FROM     googleimagefound
           GROUP BY image_id) gf ON gf.image_id = g.id
ORDER BY  COALESCE(cnt, 0) DESC

答案 3 :(得分:0)

SELECT i.*
  FROM googleimage i
  LEFT
  JOIN googleimagefound f
    ON f.image_id = i.image_id
 GROUP
    BY i.image_id
 ORDER BY COUNT(f.image_id) DESC;