我想写一个脚本来检测我的数据库中的任何重复的guest虚拟机,以便它们可以合并。
我正在尝试选择我的预订表中预订次数最多的来宾ID,因为这是我要合并的来宾。因此,如果有任何重复,它将返回一行,而id将是具有最多预订的访客。
不确定我该怎么做?
select
count(*) as duplicates,
guests.id as id,
guest_name(null, null, guests.id) as guest_name
from
guests
left join
bookings_guests_link
left join
bookings ON bookings.id = bookings_guests_link.booking_id ON guests.id = bookings_guests_link.guest_id
and bookings_guests_link.primary_client = 1
group by title , firstname , lastname , street , city , postcode , state_id
having duplicates > 1
order by count(bookings.id) desc , duplicates desc
任何帮助表示赞赏!谢谢
答案 0 :(得分:0)
这应该给你每位客人和预订的数量。
您可以使用此
创建临时表SELECT g.id, g.firstname, g.lastname, street, city, postcode, state_id,
COUNT(b.id) AS NoOfBookings
FROM guests g
LEFT JOIN bookings_guests_link bgl
ON g.id = bgl.guest_id
LEFT JOIN bookings b
ON b.id = bgl.booking_id
GROUP BY g.id, g.firstname, g.lastname
这将为您提供重复的客人列表
SELECT title, firstname, lastname, street, city, postcode, state_id
FROM guests
GROUP BY title, firstname, lastname, street, city, postcode, state_id
HAVING COUNT(id) > 1
所以你只需要找到两者之间的匹配,并决定你实际想要如何合并记录。