如何在sql中合并两个表与不同列

时间:2017-06-17 07:38:08

标签: mysql

我有两个名为booked_flatmaster_flat的表。

booked_flats的列

customer_name, customer_address, customer_phone, building_wing_no, building_name_no, flat_no

master_flats的列

building_wing_no, building_name_no, flat_no, status

当任何公寓被预订时,状态变为已售出的其他状态仍未售出。

所有已售出状态的条目都在booking_flats中。

我试图合并这两个表但是它给出了一个错误,请帮助我

$sql =  SELECT * FROM 'booked_flats' 
        UNION SELECT * FROM 'master_flats' 
            WHERE building_wing_no, building_name_no, flat_no NOT IN (
                SELECT building_wing_no, building_name_no, flat_no from booked_flats);

示例:

**master_flat:** 

 building_wing_no building_name_no flat_no status            
 -----------------------------------------------
     a                a2            104   unsold 
 -------------------------------------------------
     b                a3            105    sold




 booked_flat:
  custo_name custo_add custo_ph building_wing_no  building_name_no flat_no
  --------------------------------------------------------------------------- 
   harish     wardha     284632        b              a3           105



 I want result like 

  cust_name cust_add custo_ph building_wing_no  building_name_no flat_no status   
     harish    wardha    284632         b            a3             105            
      ---       ---       ---            a           a2             104   unsold 

1 个答案:

答案 0 :(得分:0)

我认为你真正想做的是join而不是union,但你应该更新你的问题并写下你想要展示的内容。

SELECT * FROM booked_flats b
JOIN master_flats m ON b.building_wing_no = m.building_wing_no
    AND b.building_name_no = m.building_name_no AND b.flat_no = m.flat_no;