2012-10-30 177 views
1

每個modx_site_content記錄可能在modx_site_tmplvar_contentvalues中有多個記錄。MySQL查詢子查詢或分組

我需要檢索兩個modx_site_tmplvar_contentvalues.value其中tvv.tmplvarid = 3,tvv.tmplvarid = 1,其中tvv.tmplvarid是未來的日子,我需要返回tvv.tmplvarid 3 tvv.value這是逗號分隔的標籤列表。

此查詢不返回我需要的值&我不知道如何得到我想要的。

SELECT sc.id, sc.pagetitle, tvv.value, tvv.tmplvarid, tvv.id, tvv.value 
FROM modx_site_content sc 
left join modx_site_tmplvar_contentvalues tvv on tvv.contentid = sc.id 
where published = '1' 
and (tvv.tmplvarid = '3' and tvv.value >= curdate()) 
order by sc.id; 

基本上在最後,我只需要返回的標記列表(tvv.tmplvarid = 3)在其他相關記錄(tvv.tmplvarid = 1)是將來的日期。

任何想法,這可以用分組來完成嗎?我實際上並不需要modx_site_content表中的任何內容。

回答

1

所以你需要返回兩行的標籤有1 tmplvarid和3都與同一modx_site_contentmodx_site_tmplvar_contentvalues表,但只有當3行有未來的日期時間字段?

我會做兩個獨立的連接到modx_site_tmplvar_contentvalues田部:

SELECT tOne.value, tThree.value 
FROM modx_site_tmplvar_contentvalues tOne 
INNER JOIN modx_site_content c ON tOne.contentid = c.id 
INNER JOIN modx_site_tmplvar_contentvalues tThree ON tThree.contentid = c.id 
WHERE c.published = 1 
AND tOne.tmplvarid = 1 
AND tThree.tmplvarid = 3 AND tThree.date > NOW() 

SQL小提琴:http://sqlfiddle.com/#!2/a4031/2

+0

我明白你要去哪裏,但它會返回'now'之前的值。 –

+0

SQL查詢有點不對(只是更新了sql小提琴),它有一個過去的日期不返回的行。 – theon

+0

如果在tThree.value之後添加AS日期或將AND tThree.date更改爲tThree.value,則可以工作。你的速度快了0.003秒[至少在我的測試中],所以歡呼,兩者都有效,但你的效率更高。 –

0

我想通了。驚人的,你可以做什麼,如果你剛纔讀的文檔;)

select tv.contentid, tv.value as eventdate, sc.id, sc.pagetitle, tvv.value from 
( 
select * from modx_site_tmplvar_contentvalues cv 
where cv.tmplvarid = 3 
and cv.value >= curdate() 
) as tv 
left join modx_site_content sc on sc.id = tv.contentid 
left join modx_site_tmplvar_contentvalues tvv on tvv.contentid = sc.id 
where (tvv.tmplvarid = 1) 
order by value asc 
+0

我會使用兩個連接,而不是一個子選擇 - 應該會更快。我在我的答案中列舉了一個例子。 – theon