Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query to get the data in related table

There is two table : admin , news

The structure is like this:

admin
-----
id
name

news
-----
id
createBy
updateBy

currently the createBy and updateBy stores the admin id , I would like to get the admin name of createBy and updateBy, how to achieve that? Thanks

Here is what I used in codeigniter

$this->db->select('*');
        $this->db->from('news,admin');
        $this->db->where('id', $id);
        $this->db->where('admin.id', 'news.updateBy');

Anyway the sql query is welcome, I will convert it to codeigniter syntax . Thanks for helping

like image 425
user782104 Avatar asked Jun 09 '14 06:06

user782104


People also ask

How do I get data from another table in SQL?

In SQL, to fetch data from multiple tables, the join operator is used. The join operator adds or removes rows in the virtual table that is used by SQL server to process data before the other steps of the query consume the data.

Which query is used for fetch the data from table?

The SQL SELECT statement is used to fetch the data from a database table which returns this data in the form of a result table.

What SQL clause is used to retrieve data from multiple related tables?

SQL JOIN. A JOIN clause is used to combine rows from two or more tables, based on a related column between them.


1 Answers

This is a query that will pull a particular news ID and get both the created by and updated by values from your admins table:

select
    adu.id sd as updateID,
    adu.name as updateName,
    adc.id as createID,
    adc.name as createName
from
    news ns
        left outer join admin adu
            on ns.updateBy=adu.id
        left outer join admin adc
            on ns.createBy=adc.id
where
    news.id=1

I have joined the admins table twice - as the admin updating may be different from the admin creating - and an inner join wouldn't work if either field was empty. Doing this will also allow you to pick which you want (creating or updating) but still have them in the same row of data.

If this is what you were looking for, it is a straightforward enough query and you might really benefit from reading this question and answer I put together to explain queries like this in a lot more detail. It shows and explains in detail inner and outer joins, data grouping and aggregation.

Edit: I have added column aliases to the query which means you can pick which one you want. The article I wrote and linked to also explained that in detail :)

like image 51
Fluffeh Avatar answered Oct 15 '22 14:10

Fluffeh