SQL在查询多个表时组合同一个表中的多个列

时间:2015-03-10 13:58:00

标签: mysql

我有三张表如下所示。

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

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

  3. 预订[ID,customerID,pickup_address_id,dropoff_address_id,charge,no_of_passenger]

  4. 地址表包含两种类型的地址,即拾取和丢弃。我想将两个地址中的每一个显示为一个字符串。以下是我的查询。

    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";
    

1 个答案:

答案 0 :(得分:2)

尝试CONCAT功能:

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

或CONCAT_WS函数将分隔符作为第一个参数传递:

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