You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于首个记录进行关联?MySQL多表查询技术问询

MySQL查询方案:关联邀请、通知与预约表

Hey there! I get that complex MySQL queries can feel tricky at first—let's walk through how to pull the info you need from your three tables. First, I'll assume your appointments table has an inv_id column linking it to the invites table (if that's not the actual column name, just swap it out for whatever you're using!).

1. 统计每个邀请的通知数和预约数

If you want a summary of each invite along with how many notifications and appointments are tied to it, this query will do the trick. We use LEFT JOIN to make sure even invites with no notifications or appointments show up in the results:

SELECT 
    i.id AS invite_id,
    i.name,
    i.created,
    COUNT(n.id) AS notification_count,
    COUNT(a.id) AS appointment_count
FROM invites i
LEFT JOIN notifications n ON i.id = n.inv_id
LEFT JOIN appointments a ON i.id = a.inv_id
GROUP BY i.id, i.name, i.created;

关键说明:

  • LEFT JOIN ensures every invite is included, even if it has no linked notifications or appointments.
  • COUNT(n.id) (instead of COUNT(*)) counts only actual notifications—since n.id will be NULL for invites with no notifications, those won't be counted. Same logic applies to COUNT(a.id) for appointments.

2. 列出每个邀请的具体通知和预约ID

If you need to see exactly which notification/appointment IDs are associated with each invite, use GROUP_CONCAT to list them out:

SELECT 
    i.id AS invite_id,
    i.name,
    i.created,
    GROUP_CONCAT(n.id SEPARATOR ', ') AS linked_notification_ids,
    GROUP_CONCAT(a.id SEPARATOR ', ') AS linked_appointment_ids
FROM invites i
LEFT JOIN notifications n ON i.id = n.inv_id
LEFT JOIN appointments a ON i.id = a.inv_id
GROUP BY i.id, i.name, i.created;

小提示:

If you need to filter invites by a specific date (like all invites from 2018-02-03), just add a WHERE clause before the GROUP BY:

WHERE i.created = '2018-02-03'

内容的提问来源于stack exchange,提问作者kramer65

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:31:25