如何从两个表中连接两个mysql查询

时间:2014-06-04 16:53:10

标签: php mysql

我有两个独立的查询:

查询1(此查询从我的表中获取所有图库):

$showgallerys = mysqli_query($con,"SELECT * FROM canais");
while($row = mysqli_fetch_array($showgallerys)) {
echo '<div class="canal-nome">'.$row['nome'].'</div>;

查询2(此查询计算每个类别的照片数量):

$q="SELECT categoria, COUNT(titulo) FROM galerias GROUP BY categoria ";
$res=mysqli_query($con,$q);
while($row = mysqli_fetch_array($res)){
 echo '
('. $row['COUNT(titulo)'] .')';
}

我需要显示图库的名称(查询1)和照片数量(查询2)

喜欢这个图库名称(30)

这是第一张表的结构(称为 canais ):

  id | nome            | htd     | imagem   | thumb    |
   1 | Gallery Nature  | nature  | face.jpg | thumb.jg | 
   2 | Gallery Peoples | people  | face.jpg | thumb.jg | 
   3 | Gallery Animals | animal  | face.jpg | thumb.jg | 

这是第二张表的结构(称为 galerias

  id | titulo       | foto    | thumb           | data    | categoria |
  1  | Sun          | sun.jpg | sun-thumb.jpg   | now     | nature    |
  2  | Moon         | mon.jpg | mon-thumb.jpg   | now     | nature    |
  3  | Tree         | tree.jpg| tre-thumb.jpg   | now     | nature    |
  4  | Woman        | wman.jpg| wman-thumb.jpg  | now     | people    |
  5  | Girl         | gran.jpg| gr-thumb.jpg    | now     | people    |
  6  | leaf         | lea.jpg | leaf-thumb.jpg  | now     | nature    |
  7  | dog          | dog.jpg | dog-thumb.jpg   | now     | animal    |

在这种情况下,我需要显示如下结果:

   Gallery name --> Gallery Nature (4) <-- Number of  occurrences 
   Gallery name --> Gallery People (2) <-- Number of  occurrences 
   Gallery name --> Gallery Animal (1) <-- Number of  occurrences 

作为画廊的名称必须通过&#34; canais&#34;表格和出现次数必须来自&#34; galerias&#34;表格基于&#34; categoria&#34;柱。有人可以帮我解决吗?

1 个答案:

答案 0 :(得分:2)

以下查询将为您提供帮助

SELECT a.nome AS gallery  ,COUNT(b.titulo)  AS photos 
FROM canais a INNER JOIN galerias b ON a.htd    = b.categoria 
GROUP BY a.nome