MySQL group by和counter

时间:2018-02-09 00:28:31

标签: php mysql

我有一个包含字段用户的表,bookname具有以下记录

enter image description here

我执行以下查询

/* A constructor created the old-fashioned way. */
function ExistingClass () {
  /* The object that will be assigned to this.try. */
  var shadowObj = {};
  
  /* The function that throws an error (calls illegal constructor). */
  this.func1 = function () {
    return new Element();
  };
  
  /* Iterate over every property of the context. */
  for (var func in this) {
    /* Check whether the property is a function. */
    if (this[func] && this[func].constructor == Function) {
      /* Create a shadow function of the context's method. */
      shadowObj[func] = function () {
        try { return this[func]() }
        catch (e) { console.log("Error caught: " + e.message) }
      }.bind(this);
    }
  }
  
  /* Assign the shadow object to this.try. */
  this.try = shadowObj;
}

/* Example. */
var cls = new ExistingClass;
cls.try.func1();
cls.func1();

我得到了以下输出

enter image description here

我期待这个输出

SELECT `bookname`,`user`, count(*) as total FROM `books` GROUP BY `bookname`,`user`

我没有第三张桌子。

知道我做错了什么。

1 个答案:

答案 0 :(得分:2)

你的意思是http://sqlfiddle.com/#!9/d6f8c/12

SELECT s.bookname, s.user, IF(t.count IS NULL, s.count, t.count) FROM 
(
  SELECT bookname, user, 0 AS `count` FROM
  (SELECT DISTINCT bookname FROM books) AS p,
  (SELECT DISTINCT user FROM books) AS q
) AS s LEFT JOIN
(SELECT bookname, user, COUNT(*) AS `count` FROM books GROUP BY bookname, user) AS t
ON (s.bookname = t.bookname AND s.user = t.user)

结果

a    u1   2
b    u1   1
a    u2   1
b    u2   0