user3034845
user3034845

Reputation: 125

SQL combining multiple columns from same table while querying multiple tables

I have got three tables that looks as follows.

  1. usedetails [ID,first_name,last_name,telephone,email]

  2. address [ID,streetnumber,streetname,town,county,postcode,userdetailsID]

  3. BOOKING [ID,customerID,pickup_address_id,dropoff_address_id,charge,no_of_passenger]

Address table holds two types of address ie pickoff and dropoff. I would like to display each of the two addresses as one string. The following is my query.

query = "SELECT A.streetnumber,
                        A.streetname,
                        A.town,
                        A.postcode
                    AS pickup_point
                        AB.streetnumber,
                        AB.streetname,
                        AB.town,
                        AB.postcode
                    AS  dropoff_point
                        UD.first_name,
                        UD.last_name,
                        UD.telephone,
                        UD.email
                    FROM userdetails UD 
                    INNER JOIN booking B
                    ON B.customerID = UD.ID
                    INNER JOIN address A
                    ON B.pickup_address_id = A.ID
                    INNER JOIN address AB
                    ON AB.drop_off_address_id = A.ID
                    WHERE UD.ID = A.userdetailsID OR UD.ID = AB.userdetailsID";

Upvotes: 0

Views: 49

Answers (1)

Try CONCAT function:

SELECT CONCAT(A.streetnumber,
              ' ',
              A.streetname,
              ' ',
              A.town,
              ' ',
              A.postcode) AS pickup_point, ...

Or CONCAT_WS function to pass separator as the first argument:

SELECT CONCAT_WS(' ',
                 A.streetnumber,
                 A.streetname,
                 A.town,
                 A.postcode) AS pickup_point, ...

Upvotes: 2

Related Questions