簡體   English   中英

mysql選擇主記錄和多個輔助記錄作為排序數據集

[英]mysql select primary record and multiple secondary records as sorted data set

我有兩個表: locationsevents

每個位置可以有多個事件。 我已經成功地執行了一個查詢來獲取所有位置和匹配事件,但是,這些事件將作為包含所有location數據的合並數據集返回。 我需要以某種方式將每個事件和所有事件列為子行,以便以后可以正確處理它們。

該查詢:

"select locations.*,events.* FROM locations,events WHERE locations.lid = events.lid AND locations.lid=1001"

返回合並的數據,如:

data [array 1]
   0: lid: "1001"  // location info
      name: "Johns Bar"
      address1: "123 Main St"
      ...
      ...
      eventID: "1000" // event info
      eName: "Halloween Bash"
      eDate: "2018-10-31"
      ...
      ...

是否有可能獲取特定的locations.lid和所有匹配的events.lid並將events記錄列為location數據的子集。

將會返回的內容如下:

data [array 1]
   0: lid: "1001"
      name: "Johns Bar"
      address1: "123 Main St"
      ...
      ...
      Events: [array 5]
         0: lid: "1001"
            eventID: "1000"
            eName: "Halloween Bash"
            eDate: "2018-10-31"
            ...
            ...
         1: lid: "1001"
            eventID: "1010"
            eName: "Christmas Party"
            eDate: "2018-12-17"
            ...
            ...
         2: [lid: "1001",...]
         3: [lid: "1001",...]
         4: [lid: "1001",...]

因此所有匹配的事件將始終作為單個返回行的一部分返回嗎? 沒有辦法讓輔助記錄作為子行/記錄列出嗎?

是的,這就是JOIN的工作方式。

如果沒有,那么這將迫使我執行兩個查詢...還是有另一種方法?

不,您不必運行多個查詢。

您可以在SQL返回結果集時獲取結果集,並帶有匹配的locationevent行對。 確保在SQL查詢中按location排序。

然后,當您獲取結果行時,請在客戶端應用程序的變量中跟蹤“當前”位置。 如果獲取一行並且其位置與之前看到的位置相同,則將其忽略。

偽代碼:

sql = SELECT ... FROM location JOIN event ... ORDER BY location
execute sql
location = nil
while row = fetch():
  if row[location] != location:
    print location
  end if
  location = row[location] # for next time
  print event
end while

這是處理SQL結果集的常見模式。

暫無
暫無

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

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