Search code examples
sqlcodeigniter-3

Concatenate or join multiple tables to a single table in CodeIgniter 3 without omitting rows if there is an empty cell


Assume I have 4 different tables 'user', 'favorite_book', 'books', 'user_image'. The data in the tables as below,

user:

|user_id |name|contact |dateCreated|
|--------|----_|-------|-----------|
|1       |Ani  | 9999  | 1232142   |
|2       |Aslam| 8888  | 1234563   |
|3       |Jhon | 7777  |2425325    |
|4       |Keras| 6666  |535345     |
|5       |Sudi | 5555  |453454     |

favorite_book:

|user_id|book_id|dateCreated|
|-------|-------|-----------|
|1      | xys   |           |
|3      | sdf   |           |
|4      | 7rlm  |           |
|5      | 7rlm  |           |

note: here 'user_id' 2 dose not have any favorite_book.

books

|book_id|book_name|book_author|dateCreated|
|-------|---------|-----------|-----------|
|xys    |book_1   | auth_1    | 
|7rlm   |book_3   | auth_3    |
|sdf    |book_9   | auth_9    |
|rtyu   | book_1  | auth_1    |

user_image

|user_id| img     |dateCreated|
|--     |---------|-----------|
|1      |Ani.png  |           |
|2      |Aslam.png|           |
|3      |NULL     |           |
|4      |NULL     |           |
|5      |Sudi.png |           |

note: few users did not provide user_image which is marked as NULL

expected solution: I need to create a table which combine all the tables to get detailed information of user at a glance. The expected solution is as follows.

|user_id|name |contact|img      |book_name|dateCreated|
|-------|-----|-------|---------|---------|-----------|
|1      |Ani  | 9999  | Ani.png |book_1   |1232142    |
|2      |Aslam| 8888  |Aslam.png||1234563 |           |
|3      |Jhon |  7777 |         |book_9   |2425325    |
|4      |Keras| 6666  |         |book_3   |535345     |
|5      |Sudi | 5555  |Sudi.png |book_3   |4534543    |

note: dateCreated is from 'user' table.

I created the table by combining all the tables with help of $this->db->join(), however it omits the rows if there is an empty or null cell. I would like to get a table with all available information.


Solution

  • that would be like this :

    SELECT
        u.user_id
        , name
        , contact
        , img
        , book_name
        , u.dateCreated
    FROM
        users                   u
        JOIN user_image         ui
            ON u.user_id = ui.user_id
        LEFT JOIN favorite_book fb
            ON u.user_id = fb.user_id
        LEFT JOIN books         b
            ON bf.book_id = b.book_id;
      on bf.book_id = b.book_id