select 多表关联查询

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了select 多表关联查询相关的知识,希望对你有一定的参考价值。

A表有:店仓ID,零售数量
B表有:店仓ID,销售数量
C表有:店仓ID,库存数量
D表有,店仓ID,店仓名称
4个表id相同

现在需要查询出来结果,店仓名称,零售数量,销售数量,库存数量

参考技术A select 店仓名称,零售数量,销售数量,库存数量

from A left join B on A.ID=B.ID left join C on A.ID = C.ID lieft join D on A.ID = D.ID本回答被提问者采纳

CI 框架多表关联查询

public function getCollectData($limit, $page, $search_user, $search_phone, $orderfield, $ordertype)
    {
        $this->db->select(‘a.id,a.mobile,a.is_del,a.register_ip,a.add_time,
        b.parent_id as master_id,
        ifnull(inv.award,0) as invite_moneys,
        ifnull(bro.price,0) as brokerage_moneys,
        ifnull(sha.read_price,0) as share_moneys,
        ifnull(sha.counts,0) as share_counts,
        (ifnull(inv.award,0)+ifnull(bro.price,0)+ifnull(sha.read_price,0)) as total_moneys);
        $this->db->from(self::$table_name . ‘ a‘);
        $this->db->join(‘ws_invitation b‘, ‘a.id = b.user_id‘, ‘left‘);
        $this->db->join(‘(SELECT sum(award) as award,user_id FROM ws_invitation_log GROUP BY user_id) as inv‘, ‘a.id = inv.user_id‘, ‘left‘);
        $this->db->join(‘(SELECT sum(price) as price,prentice_id FROM ws_brokerage_log GROUP BY user_id) as bro‘, ‘a.id = bro.prentice_id‘, ‘left‘);
        $this->db->join(‘(SELECT sum(read_number*read_price) as read_price,count(id) as counts,
        user_id FROM ws_share_record GROUP BY user_id) as sha‘, ‘a.id = sha.user_id‘, ‘left‘);
        $this->db->where([‘is_channel‘ => 0]);

        if ($search_user) {
            $this->db->where([‘a.id‘ => $search_user]);
        }
        if ($search_phone) {
            $this->db->like(‘a.mobile‘, $search_phone, ‘both‘);
        }
        if ($orderfield && $ordertype) {
            $this->db->order_by($orderfield . ‘ ‘ . $ordertype);
        } else {
            $this->db->order_by(‘a.id DESC‘);
        }
        $this->db->group_by(‘a.id‘);
        $this->db->limit($limit, $limit * ($page - 1));
        return $this->db->get()->result_array();
    }

以上是关于select 多表关联查询的主要内容,如果未能解决你的问题,请参考以下文章

如何实现多表关联查询

mysql查询语句 和 多表关联查询 以及 子查询

sql mysql多表如何关联查询

MySQL的多表关联查询

向高手请教一个SQL多表关联查询排序的问题

JDBC MySQL 多表关联查询查询