任何人都可以告诉我是否可以使用自联接将以下两个查询合并为一个,如果是,该怎么做?
查询1:
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_content
中照片的相册名称。 ugc_content
包含相册和相片的行。代表照片的rows
的{{1}}是父行的parent_content_id
。我无法更改表格或数据库结构。
目前我正在为查询1中的每个结果行运行一个新查询(query2),这是次优的; - )
谢谢!
答案 0 :(得分: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
希望这有效!
答案 1 :(得分: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
你可能不得不把“嗯”。在value
,name
和moderation_status
之前,如果它们来自ugc_meta,那么这个值是否会取自um
og {{1} }。
答案 2 :(得分:0)
您应该能够使用不同的别名简单地使用LEFT JOIN到ugc_meta表,以实现您的父表连接,如下所示:
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来提高你的性能提升。