MySQL查询不适用于我Codeigniter Php

时间:2019-03-03 09:37:14

标签: php mysql sql codeigniter join

我正在使用带有Codeigniter的mysql,这是我的表结构:

表A:

while iterations > 0:
    u,v = lucas_kanade(image1, image2)

    new_image = warp(image1)

表B:

id(doctorid)            name    
-----------------------------
1                       abc
2                       xyz
3                       ahd
4                       djd

现在我想获取所有具有类型计数的医生记录,我想要以下结果:

id          doctor_id       type
-------------------------------------
1           1               Nuter
2           3               Spay

我尝试使用以下代码,但对我不起作用,该怎么办?

id          name        Nuter     Spay
---------------------------------------
1           abc         1         0
2           xyz         0         Spay

2 个答案:

答案 0 :(得分:1)

尝试此代码:

$this->db->select('A.*,B.type');
$this->db->from('A');
$this->db->join('B', 'B.doctor_id = A.id');
$query = $this->db->get();

答案 1 :(得分:0)

似乎您正在寻找条件聚合。

在纯SQL中,查询应类似于:

SELECT
    A.id,
    A.name,
    SUM(CASE WHEN B.type = 'Nuter' THEN 1 ELSE 0 END) as Nuter,
    SUM(CASE WHEN B.type = 'Spay' THEN 1 ELSE 0 END) as Spay
FROM A
INNER JOIN B ON B.doctor_id = A.id
GROUP BY A.id, A.name

如果表A和B之间的关系为1-1,而不是1-N(如示例数据所示),则可以简化为:

SELECT
    A.id,
    A.name,
    CASE WHEN B.type = 'Nuter' THEN 1 ELSE 0 END as Nuter,
    CASE WHEN B.type = 'Spay' THEN 1 ELSE 0 END as Spay
FROM A
INNER JOIN B ON B.doctor_id = A.id

尝试:

$this->db->select(
    "A.id,
    A.name,
    CASE WHEN B.type = 'Nuter' THEN 1 ELSE 0 END as Nuter,
    CASE WHEN B.type = 'Spay' THEN 1 ELSE 0 END as Spay"
);
$this->db->from('A');
$this->db->join('B', 'B.doctor_id = A.id');
$query = $this->db->get();