如何将这2个查询的2个查询合并为1个查询?

时间:2011-09-05 07:30:43

标签: mysql

我有2个表,我需要查询相似内容但不同的字段名称。

我想将以下2个查询合并为1,以便我有1组结果。

2个查询是:

  SELECT 
    bookings.booking_name,
    bookings.booking_email,
    bookings.booking_mobile
  FROM 
    bookings   
  WHERE 
  ( bookings.booking_email LIKE "%' . $_POST['val'] . '%"
  OR 
    bookings.booking_name LIKE "%' . $_POST['val'] . '%"
  OR 
    bookings.booking_mobile LIKE "%' . $_POST['val'] . '%"
  )


SELECT 
    purchases.customer_name,
    purchases.customer_email,
    purchases.customer_phone
FROM 
 handbags
WHERE   
  ( purchases.customer_email LIKE "%' . $_POST['val'] . '%"
  OR 
    purchases.customer_name LIKE "%' . $_POST['val'] . '%"
  OR 
    purchases.customer_phone LIKE "%' . $_POST['val'] . '%"
  )

如何完成这种事情,以便在我的结果中,只需通过“电子邮件”即可访问customer_email和booking_email。

2 个答案:

答案 0 :(得分:2)

union [all]他们在一起:

select ...
union
select ...

添加'all'将允许重复。

答案 1 :(得分:1)

将两个查询与UNION运算符组合在一起,并为列提供与名称匹配的内容。

(SELECT 
  bookings.booking_name AS name,
  bookings.booking_email AS email,
  bookings.booking_mobile AS phone
FROM 
  bookings   
WHERE 
( bookings.booking_email LIKE "%' . $_POST['val'] . '%"
  OR 
  bookings.booking_name LIKE "%' . $_POST['val'] . '%"
  OR 
  bookings.booking_mobile LIKE "%' . $_POST['val'] . '%"
))
UNION
(
SELECT 
  purchases.customer_name AS name,
  purchases.customer_email AS email,
  purchases.customer_phone AS phone
FROM 
 handbags
WHERE   
( purchases.customer_email LIKE "%' . $_POST['val'] . '%"
  OR 
  purchases.customer_name LIKE "%' . $_POST['val'] . '%"
  OR 
  purchases.customer_phone LIKE "%' . $_POST['val'] . '%"
));