簡體   English   中英

以一對多關系連接 MYSQL 中的兩個表,但僅顯示第二個表中的一個條目

[英]Joining two tables in MYSQL with a one to many relationship, but displaying only one entry from the second table

如果我有兩個表,Consumer 和 Appointment,是否有辦法加入它們,以便只顯示最近的約會? 我能夠用 sql 服務器做到這一點,但 mysql 似乎有點不同。

我原以為要執行此操作的查詢是

SELECT Con.ConsumerID, 
       Con.ConsumerName,
       App.AppointmentID, 
       App.ScheduledDate, 
       App.Location 
FROM Consumer Con 
LEFT JOIN Appointment AS App 
  ON Con.ConsumerID = (SELECT ConsumerID 
                       FROM Appointment AS App2 
                       WHERE App2.ConsumerID = Con.ComsumerID 
                       ORDER BY ScheduledDate 
                       DESC 
                       LIMIT 1)

這似乎返回了所有具有所有約會的消費者,所以我有很多重復的消費者。

我的桌子看起來像

  • 消費者

    • 消費者ID
    • 消費者姓名
  • 預約

    • 預約ID
    • 消費者ID
    • 約定的日期
    • 地點

使用下面的查詢。

SELECT Consumer.ConsumerName FROM Consumer WHERE Consumer.ConsumerID=(SELECT Appointment.AppointmentID FROM Appointment ORDER BY Appointment.ScheduledDate DESC LIMIT 1)

為了從兩個表中檢索所有數據,您可以在 Appointment 的 select 中進行上述查詢。

SELECT * FROM Appointment where ConsumerID=(SELECT Consumer.ConsumerID FROM Consumer WHERE Consumer.ConsumerID=(SELECT Appointment.AppointmentID FROM Appointment ORDER BY Appointment.ScheduledDate DESC LIMIT 1))

我讓它工作了。 我想多了。

SELECT
                        Con.ConsumerID,
                        Con.ConsumerName
                        App.AppointmentID,
                        App.ScheduledDate,
                        App.Location
                    FROM
                        Consumer Con
                    LEFT JOIN Appointment AS App
                    ON App.AppointmentID = (
                    SELECT AppointmentID
                    FROM Appointment AS App2
                    WHERE App2.ConsumerID = Con.ConsumerID
                    ORDER BY ScheduledDate DESC LIMIT 1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM