Yii2 MySQL按关系计数排序

时间:2016-03-01 03:54:59

标签: php yii2

表1 - 用户:

ID Name
1 Jonh
2 Mark
3 King

表2 - 书籍:

ID user_id {{1 }} status
... 1 1 1
... 2 1 1
... 3 1 1
... 4 2 1
... 5 1 0
... 6 1 0

代码:

...      

问题:

$query = User::find(); $query->joinWith('books'); $query->select(['user.*', 'COUNT(book.id) AS booksCount']); $query->andWhere(['book.status' => 1]); // Problem Here! $query->groupBy(['user.id']); $query->orderBy(['booksCount' => SORT_DESC]); 工作正常,但它没有以query返回用户。 如果我删除了行id = 3,它可以正常工作并返回所有用户。

我应该更改哪些内容列出所有用户,即使是那些没有$query->andWhere(['book.status' => 1]);相关图书的用户?

2 个答案:

答案 0 :(得分:2)

我找到了答案:

Compile

答案 1 :(得分:-1)

如果图书的状态为0或1,则可以使用COUNT(book.id)来获取用户拥有的图书数量,而不是使用SUM(book.status)。然后,您可以删除WHERE book.status = 1条款,它会返回所有用户拥有的图书数量,即使在用户3拥有0本图书的情况下也是如此。

问题

真正的问题在于你的where子句。由于WHERE在分组之前处理,而用户3没有任何行where book.status = 1,因此用户没有包含在基本查询中的行。因此,在分组期间/之后用户不会出现。

如果您想要了解可以根据条件计算行数的全部案例,使用COUNT(CASE WHEN book.status IS NULL THEN NULL ELSE NULLIF(0,book.status) END)也会为您提供您正在寻找的结果。由于COUNT()不会计算表达式为NULL的行,因此book.status允许#include <sstream> void LinkedList::printList(std::ostream& os = std::cout) { size_t counter = 0; std::ostringstream indx; std::ostringstream value; for( ListNode *current = head; current != NULL; current = current->next ) { indx << counter++ << "\t"; value << current->data << "\t"; } os << indx.str().c_str() << std::endl << value.str().c_str() << std::endl; } 为-1,1,2和任何其他数字,只要它不是&#39; t 0(或用户3的情况下为NULL),仍然包含在计数中。