3

I am working with mysql with codeigniter, hHere is my table structure:

Table A:

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

Table B:

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

Now I want to get all records of doctor with count of type, I want the following result:

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

I tried with following code but not working for me, how can I do this ?

$this->db->select('A.*');
$this->db->from('A');
$this->db->join('B', 'B.doctor_id = (SELECT COUNT(Type) FROM B )');
$query = $this->db->get();
1
  • 1
    The join condition seems to be wrong. Commented Mar 3, 2019 at 10:06

2 Answers 2

1

Try this code:

$this->db->select('A.*,B.type');
$this->db->from('A');
$this->db->join('B', 'B.doctor_id = A.id');
$query = $this->db->get();
Sign up to request clarification or add additional context in comments.

Comments

0

It seems like you are looking for conditional aggregation.

In pure SQL, the query should look like:

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

If you have a 1-1 relationship between tables A and B instead of 1-N (as your sample data suggests), then this can be simplified as:

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

Try:

$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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.