2

谁能告诉我是否可以使用自联接将以下两个查询合并为一个,如果可以,该怎么做?

查询一:

   SELECT pm.username AS user,
          uc.content_id AS id,
          value AS filename,
          name,
          moderation_status AS status,
          uc.parent_content_id
     FROM myweb.ugc_meta um
LEFT JOIN myweb.ugc_content uc ON uc.content_id = um.item_id
LEFT JOIN myweb.userbase_member pm ON uc.user_id = pm.id
    WHERE uc.content_type ='my.photo'
      AND uc.promoted = '1'
      AND moderation_status='passed'
    LIMIT 10

查询 2:

SELECT value
  FROM myweb.ugc_meta um
 WHERE um.item_id = '4780c650137a3409901286'
-- (item_id is the content_parent_id from query 1)

ugc_meta包含 中照片的相册名称ugc_contentugc_content包含相册和照片的行。rows代表照片有一个parent_content_id这是content_id父行。我没有更改表或数据库结构的选项。

目前,我正在为查询 1 中的每个结果行运行一个新查询 (query2),这是次优的;-)

谢谢!

4

3 回答 3

1

如果你想自加入一个表,你必须为每个表分配一个不同的别名,那么它应该可以正常工作

   SELECT pm.username AS user,
          uc.content_id AS id,
          um.value AS filename, um2.value AS filename2
          um.name, um2.name AS name2
          moderation_status AS status,
          uc.parent_content_id
     FROM myweb.ugc_meta um
LEFT JOIN myweb.ugc_content uc
       ON uc.content_id = um.item_id
LEFT JOIN myweb.userbase_member pm
       ON uc.user_id = pm.id
LEFT JOIN myweb.ugc_meta um2
       ON id = um2.item_id
    WHERE uc.content_type ='my.photo'
      AND uc.promoted = '1'
      AND moderation_status='passed'
    LIMIT 10

希望这有效!

于 2009-12-01T12:31:30.083 回答
1

这应该这样做:

SELECT pm.username AS user,
      uc.content_id AS id,
      value AS filename, 
      name,
      moderation_status AS status,
      um2.value AS 
FROM myweb.ugc_meta um
LEFT JOIN myweb.ugc_content uc ON uc.content_id = um.item_id
LEFT JOIN myweb.userbase_member pm ON uc.user_id = pm.id
LEFT JOIN myweb.ugc_meta om2 ON um2.item_id = uc.parent_content_id
WHERE uc.content_type ='my.photo'
  AND uc.promoted = '1'
  AND moderation_status='passed'
LIMIT 10

您可能必须输入“嗯”。,如果它们来自 ugc_meta valuename否则moderation_status将不明确该值是否来自umog um2

于 2009-12-01T12:39:29.533 回答
0

您应该能够使用不同的别名简单地对 ugc_meta 表使用 LEFT JOIN 来实现父表连接,如下所示:

SELECT pm.username AS user,
          uc.content_id AS id,
          value AS filename,
          name,
          moderation_status AS status,
          uc.parent_content_id,
          parent.`value`
     FROM myweb.ugc_meta um
LEFT JOIN myweb.ugc_content uc ON uc.content_id = um.item_id
LEFT JOIN myweb.ugc_meta parent ON uc.parent_content_id = parent.item_id
LEFT JOIN myweb.userbase_member pm ON uc.user_id = pm.id
    WHERE uc.content_type ='my.photo'
      AND uc.promoted = '1'
      AND moderation_status='passed'
    LIMIT 10

我使用了 LEFT JOIN 是因为子表中可能并不总是有 parent_content_id,如果在这种情况下总是有父项,那么您可以使用 INNER JOIN 来增加您的性能收益。

于 2009-12-01T12:38:05.247 回答