开发者

Geting data: Complex MySQL query, vs PHP cycles

Ok, here is my problem.

I have a table, lets call it Mails. The primary key is MailId. Ths table has a on to many relationship with a table Items, which has the primary key ItemId and references the Mail with Items.MailId . And then there is a table called Templates, which has a one to one relationship with the Items, Templates.ItemId=Items.ItemId.

What I want to know, what is the most efficient way to get this data:

MailId --------------------- ItemId[TemplateId], ItemId[TemplateId], ItemId[TemplateId], ItemId [TemplateId]

SO what I'm trying to draw here is a row, where in a table there is a cell with the MailId then a cell, that contains all of the Items referencing this MailId, and each item is a link that either point to the add or edit page, depending on if this item has a template.

My Solution

I first fetch all of the Mails, and开发者_JAVA技巧 then run the Array through a foreach() loop in PHP, and on every iteration get the ItemId's for this Mail. The query I use to get the ItemId's has a subquery, that counts the references to this Item, and return either a 1 or a 0. It looks something like this:

SELECT `Items`.*,`Items`.ItemId as wid,(SELECT 
count(templateId) from `Templates` where ItemId=wid) as
templateCount from `Item` where MailId=$id 

This works, but I hate using cycles for something, that I think could be done with a query. Is this possible, and if yes, how?

Thanks!


Yes you can and should do it in one query.

SELECT
  Mails.MailId,
  Items.*,
  COUNT(Templates.ItemId)
FROM
  Mails
INNER JOIN
  Items
ON
  Mails.MailId = Items.MailId
LEFT OUTER JOIN
  Templates
ON
  Templates.ItemId = Items.ItemId
GROUP BY
  Mails.MailId, Items.ItemId
ORDER BY
  Mails.MailId, Items.ItemId

Your PHP code will be slightly different, since you have only one loop over the rows. You need to look at the MailId to know when to start a new row in your HTML (when the MailId of the current row is different from the last row).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜