我有一个包含以下字段和示例数据的表:
user_id meta_key meta_value
------- -------- ----------
'69' 'usertemplate' 'template1'
'69' 'userstartdate' '07/26/2012 02:01:37 PM'
'69' 'userenddate' '07/26/2013 02:01:37 PM'
'70' 'usertemplate' 'template1'
'70' 'userstartdate' '07/26/2013 02:01:37 PM'
'70' 'userenddate' '07/26/2014 02:01:37 PM'
'71' 'usertemplate' 'template2'
'71' 'userstartdate' '07/26/2012 02:01:37 PM'
'71' 'userenddate' '07/26/2013 02:01:37 PM'
'72' 'usertemplate' 'template2'
'72' 'userstartdate' '07/26/2011 02:01:37 PM'
'72' 'userenddate' '07/26/2012 02:01:37 PM'
'73' 'usertemplate' 'template2'
'73' 'userstartdate' '07/25/2011 02:01:37 PM'
'73' 'userenddate' '07/25/2012 02:01:37 PM'
我的目标是获取** user_id **的列表,其中(例如):
usertemplate = template2
userstartdate> 07/20/2011 02:01:37 PM
userstartdate< 07/30/2011 02:01:37 PM
我该如何撰写此查询?
编辑:这是我到目前为止所尝试的:
SELECT user_id
FROM myTable t
INNER JOIN myTable s
ON t.user_id = s.user_id
AND s.meta_key = 'userstartdate'
AND CAST(s.meta_value AS DATE) > '07/20/2011 02:01:37 PM'
INNER JOIN myTable e
ON t.user_id = e.user_id
AND e.meta_key = 'userenddate'
AND CAST(e.meta_value AS DATE) < '07/30/2011 02:01:37 PM'
WHERE t.meta_key = 'usertemplate'
AND t.meta_value = 'template2'
答案 0 :(得分:1)
你可以通过几个自连接来实现这个目的:
SELECT user_id
FROM myTable t
INNER JOIN myTable s ON t.user_id = s.user_id
AND s.meta_key = 'userstartdate'
AND CAST(s.meta_value AS DATE) > '07/20/2011 02:01:37 PM'
INNER JOIN myTable e ON t.user_id = e.user_id
AND e.meta_key = 'userenddate'
AND CAST(e.meta_value AS DATE) < '07/30/2011 02:01:37 PM'
WHERE t.meta_key = 'usertemplate' AND t.meta_value = 'template2'
我将把转换的确切语法留给日期数据类型并将其作为练习进行比较。 :)
答案 1 :(得分:0)
这应该有效:
SELECT DISTINCT T.user_id
FROM tbl T
INNER JOIN tbl T1
on T.user_id = T1.user_id
AND T1.meta_key = 'usertemplate'
AND T1.meta_value = 'template2'
INNER JOIN tbl T2
on T.user_id = T2.user_id
AND T2.meta_key = 'userstartdate'
AND T2.meta_value > '07/20/2011 02:01:37 PM'
AND T2.meta_value < '07/30/2011 02:01:37 PM'