Implementing a WHERE clause within a subquery for the value of a pivot column?

夙愿已清 提交于 2019-12-24 20:16:59

问题


I've successfully managed to perform a few table joins and generate a result using a pivot table (with the aid of Ollie Jones). The sql statement and result are below.

I'd like the results returned to only have rows with values of pivot column 'date' (I think that's the terminology!?) set for today or in the future. From what I can see WHERE date >= CURDATE() should do the job however because 'date' doesn't technically exist I receive an error on execution when added to the WHERE clause at the end of the statement. I'm not sure how to integrate it into my second subquery, any help would be hugely appreciated :)

Thanks in advance

SELECT 
    content.id as id, content.alias as alias,

    ( 
        SELECT modx_site_tmplvar_contentvalues.value FROM modx_site_tmplvar_contentvalues 
        WHERE modx_site_tmplvar_contentvalues.tmplvarid = 324 
        AND modx_site_tmplvar_contentvalues.contentid = content.id 
     ) AS featured, 

    ( 
        SELECT modx_site_tmplvar_contentvalues.value FROM modx_site_tmplvar_contentvalues 
        WHERE modx_site_tmplvar_contentvalues.tmplvarid = 289 
        AND modx_site_tmplvar_contentvalues.contentid = content.id

     ) AS date

    FROM modx_site_content AS content 

    LEFT JOIN 
        modx_site_tmplvar_contentvalues AS tv_values
        ON tv_values.contentid = content.id 

    WHERE content.parent = 1842 
     AND content.published = 1 

    GROUP BY tv_values.contentid 
    ORDER BY featured DESC, date ASC

回答1:


One option si to change section of "date" and do it with "left join":

SELECT 
    content.id as id, content.alias as alias,

    ( 
        SELECT modx_site_tmplvar_contentvalues.value FROM modx_site_tmplvar_contentvalues 
        WHERE modx_site_tmplvar_contentvalues.tmplvarid = 324 
        AND modx_site_tmplvar_contentvalues.contentid = content.id 
     ) AS featured, 

    date_values.value as date

    FROM modx_site_content AS content 

    LEFT JOIN 
        modx_site_tmplvar_contentvalues AS tv_values
        ON tv_values.contentid = content.id

    LEFT JOIN
        modx_site_tmplvar_contentvalues AS date_values
        ON date_values.contentid = content.id

WHERE content.parent = 1842 
    AND content.published = 1 
    AND date_values.tmplvarid = 289
    AND date_values.value >= CURDATE() 

GROUP BY tv_values.contentid 
ORDER BY featured DESC, date ASC


来源:https://stackoverflow.com/questions/17356887/implementing-a-where-clause-within-a-subquery-for-the-value-of-a-pivot-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!