计算mysql中列的行数

时间:2017-06-18 08:51:22

标签: mysql laravel

我的问题很简单。我有两张桌子

transaction_bodies
------------------
body_id
full_name

另一个是

transaction_accounts
--------------------
account_id
body_id
account_name

关系是one to many。一个机构可以拥有多个帐户。我正在尝试创建一个查询机构拥有的帐户的查询。

我试过这个

  SELECT * 
  FROM 
  (
      SELECT count(*) as trans, tb.full_name 
      FROM transaction_accounts ta 
      LEFT JOIN transaction_bodies tb 
      ON tb.body_id = ta.body_id
   ) as row;

但这并没有给出正确的结果。任何人都可以帮我解决这个问题吗? 如果可以提供如何在Laravel中编写子查询,那将是一个很受欢迎的。

4 个答案:

答案 0 :(得分:1)

您可以使用LEFT JOIN,例如:

SELECT tb.body_id, COUNT(ta.*)
FROM transaction_bodies LEFT JOIN transaction_accounts ta
ON tb.body_id = ta.body_id
GROUP BY tb.body_id;

答案 1 :(得分:1)

使用简单的LEFT JOIN即可实现

SELECT tb.full_name, COUNT(account_id) as accounts
FROM transaction_bodies tb LEFT JOIN transaction_accounts ta
ON tb.body_id = ta.body_id
GROUP BY tb.body_id;

在Laravel中你可以像模型

那样做
$accounts = Transaction_body::leftJoin('transaction_accounts as ta','transaction_bodies.body_id','ta.body_id')->groupBy('transaction_bodies.body_id')->get();

没有模特

$accounts = DB::table('transaction_bodies')->leftJoin('transaction_accounts as ta','transaction_bodies.body_id','ta.body_id')->groupBy('transaction_bodies.body_id')->get();

答案 2 :(得分:1)

试试这个:

$result = DB::table('transaction_bodies')
         ->leftJoin('transaction_accounts as 
                              ta','transaction_bodies.body_id','ta.body_id')
          ->select(DB::raw('count(ta.account_id) AS trans'),'transaction_bodies.full_name')
          ->groupBy('transaction_bodies.body_id')

         ->get();

答案 3 :(得分:1)

            /**
             * Class Body
             */
            class Body extends Model
            {
                /**
                 * The database table used by the model.
                 *
                 * @var string
                 */
                protected $table = 'transaction_bodies';

                /**
                 * Get the accounts for the Transaction Body.
                 */
                public function accounts()
                {
                    return $this->hasMany(Account::class);
                }
            }

            /**
             * Class Account
             */
            class Account extends Model
            {
                /**
                 * The database table used by the model.
                 *
                 * @var string
                 */
                protected $table = 'transaction_accounts';

                /**
                 * Get the body that owns the account.
                 */
                public function body()
                {
                    return $this->belongsTo(Body::class);
                }
            }

            //usage
            $accounts = Body::find(1)->accounts;

https://laravel.com/docs/5.4/eloquent-relationships#one-to-many