Laravel雄辩的子查询别名

时间:2019-02-12 08:34:22

标签: subquery laravel-5.1

如何在Laravel 5.1中做到这一点?

SELECT *
FROM
(
    SELECT subscriber_id, COUNT(*) as count
        FROM mailing_group_subscriber
        WHERE mailing_group_id IN ('99', '15498855416270870')
    GROUP BY subscriber_id
) table_count
WHERE count = 2;

谢谢!

1 个答案:

答案 0 :(得分:0)

您的查询未使用having,因此将全部计数并选择计数为2。因此,获取所有计数,然后通过集合选择计数2:

DB::table('mailing_group_subscriber')
  ->select(DB::raw('COUNT(*) as count'))
  ->select('subscriber_id')
  ->groupBy('subscriber_id')
  ->whereIn('mailing_group_id', ['99', '15498855416270870'])
  ->pluck('count', 'subscriber_id')
  ->where('count', 2);