我有一个mysql表,其结构如下: order_id - customer_name - customer_email_address
我需要进行查询以搜索具有相同customer_name或相同customer_email的记录,并显示order_id组排序的结果(降序)。
示例:
Mysql表
order_id customer_name customer_email_address
1 pippo pippo@pippo.com
2 pippo pippo2@pippo2.com
3 pluto pluto@pluto.com
4 caio pippo@pippo.com
5 pippo4 pippo4@pippo4.com
6 pluto pluto22@pluto22.com
结果
6 pluto pluto22@pluto22.com
3 pluto pluto@pluto.com
4 caio pippo@pippo.com
1 pippo pippo@pippo.com
2 pippo pippo2@pippo2.com
结果6和3共享相同的customer_name 结果4和1共享相同的customer_email_address 结果1和2共享相同的customer_name
Order_id 5不在结果中,因为它没有重复项。
答案 0 :(得分:0)
试试这个:
SELECT
order_id,
customer_name,
customer_email_address
FROM
my_table
WHERE
order_id IN (
SELECT
order_id
FROM
my_table
GROUP BY
customer_name
HAVING
COUNT(*)>1
UNION
SELECT
order_id,
FROM
my_table
GROUP BY
customer_email_address
HAVING
COUNT(*)>1
)
ORDER BY
customer_name,
customer_email_address,
order_id DESC