使用不同的WHERE子句合并2个查询

时间:2014-11-02 19:54:09

标签: php mysql

我有以下查询:

select
*
from 
(
SELECT art_titel as at, COUNT(*) as Number1
FROM artikel_views 
WHERE user_id != ''  
GROUP BY art_titel 
ORDER BY Number1 desc
) as FirstSet
join
(
SELECT art_titel as at, COUNT(*) as Number2
FROM artikel_views 
WHERE user_id = ''  
GROUP BY art_titel 
ORDER BY Number2 desc
) as SecondSet
on FirstSet.at = SecondSet.at

我的HTML表格:

<table>
  <tr>
    <td>Art Titel</td>
    <td>user_id is NULL</td>
    <td>user_id is not NULL</td>
  </tr>

<?php while($row = mysql_fetch_assoc($res)) { ?>

  <tr>
    <td><?php echo $row['at']; ?></td>
    <td><?php echo $row['Number2']; ?></td>
    <td><?php echo $row['Number1']; ?></td>
  </tr>

<?php } ?>

</table>

我所做的是将$ row [&#39; Number1&#39;]和$ row [&#39; Number 2&#39;]中的值与art_titel结合使用。 此查询的结果并不好。我在两个查询中只有art_titel上匹配的art_titel和art_views,但它并不好。我想要两种方式的所有项目。

我也尝试过UNION,但是我的工作方式并没有。

1 个答案:

答案 0 :(得分:0)

不需要2个查询,只需使用CASE条件。

SELECT art_titel as at, SUM(CASE WHEN user_id != '' THEN 1 ELSE 0 END) as Number1,
SUM(CASE WHEN user_id = '' THEN 1 ELSE 0 END) as Number2
FROM artikel_views 
GROUP BY art_titel 
ORDER BY Number1 desc,Number2 desc