Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Select the same column, twice

I don't know if it is correct, but look the following schema:

enter image description here

An Entity can be either a Carrier or a Customer. Every customer must be associated with a Carrier, this Carrier can be the own Customer.

I'm stuck, tried without success to perform a single query that returns the NAME of the customer and the NAME of his Carrier. Is there a way to make such operation ?

Thanks

like image 862
Caio Avatar asked Apr 01 '26 06:04

Caio


1 Answers

Join entity twice and give the name column aliases. Remove the last join if additional carrier fields are not needed.

select customer_entity.name as customer_name, customer.credit, -- additional customer fields...
        carrier_entity.name as carrier_name, carrier.carrier_stuff -- additional carrier fields...
        from entity as customer_entity
        inner join customer on (customer.id_entity = customer_entity.id_entity)
        inner join entity as carrier_entity on (customer.id_carrier = carrier_entity.id_entity)
        inner join carrier on (carrier.id_entity = carrier_entity.id_entity)
like image 103
gmm Avatar answered Apr 02 '26 20:04

gmm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!