是否可以编写单个查询?

时间:2015-11-26 09:58:03

标签: mysql

第一张表:问题

+----+-----------+----------+------------+-------------+----------+-----------+-----------+-------+
| id | createdBy | question | attachment | contributor | doctorId | ipAddress | userAgent | views |
+----+-----------+----------+------------+-------------+----------+-----------+-----------+-------+
|  1 |         1 | hiii     | NULL       | NULL        |        3 | NULL      | NULL      |  NULL |
+----+-----------+----------+------------+-------------+----------+-----------+-----------+-------+

第二张表:视图

+----+-----------+--------+-------+------------+
| id | ipAddress | userId | count | questionId |
+----+-----------+--------+-------+------------+
|  1 | NULL      |      1 |  NULL |          1 |
+----+-----------+--------+-------+------------+

我想要数据问题表id,createdBy,question,count(从view表中查看问题的用户数= = 1); 如何编写单个查询;

2 个答案:

答案 0 :(得分:1)

一个简单的COUNT(DISTINCT ......)应该这样做: -

SELECT COUNT(DISTINCT userId)
FROM view
WHERE question = 1

要获得有关问题的其他详细信息,请执行连接并添加GROUP BY子句

SELECT question.id,
        question.createdBy,
        question.question,
        COUNT(DISTINCT userId)
FROM view
INNER JOIN question
WHERE view.question = 1
GROUP BY id,
        createdBy,
        question

答案 1 :(得分:0)

如果表名是问题而你的问题也是一个包含问题编号(id)的字段,而views字段包含问题的观看次数,那么你可以得到这样的观点。

select views from question where question=1;