考虑两个(或更多)查询的UNION:
SELECT activity AS activity1, completion AS status1, date_end AS date1
FROM activities
WHERE (
matter LIKE '%JR161167'
AND activity LIKE '1.1 %'
AND DATEDIFF( CURDATE( ) , date_end ) <120
)
UNION
SELECT activity AS activity2, completion AS status2, date_end AS date2
FROM activities
WHERE (
matter LIKE '%JR161167'
AND activity LIKE '1.2 %'
AND DATEDIFF( CURDATE( ) , date_end ) <120
)
活动列将包含变量字符串值,但该字符串将可靠地添加到1.1
或1.2
或1.3
一直到1.9
。
问题列也是一个字符串,但会可靠地附加一个类似于JR161167
的帐号。
我想查询过去120天内具有date_end的所有记录(即DATEFIFF
部分),与指定的帐号(JR161167)匹配,但活动字段包含任何和所有子字符串“1 名词的”。
使用UNION从单个表“活动”返回正确的数据,但似乎没有办法在第一个查询的列或别名下标题结果集。相反,我想要像:
activity1 status1 date1 activity2 status2 date2
--------------------------------------------------------------------------------
1.1 Step 1 begins... Incomplete 2017-4-16 1.2 Step 2 begins... Incomplete 2017-4-30
相反,我的查询在一个别名列标题activity1
下堆叠所有结果,无论它们是否包含1.1,1.2,1.3等。与日期和完成字段数据相同,它不会很好地排序到相应的date1,date2等,或status1,status2等。
我最近读了一个看起来像这样的例子,它看起来像我想要实现的逻辑,我想知道是否有人能理解它的意图并帮助我制定正确的查询:
SELECT date_end
IF( WHERE description LIKE '1.1 %') AS date1,
IF( WHERE description LIKE '1.2 %') AS date2`
FROM activities
答案 0 :(得分:1)
查询1 :
SELECT a1.*, a2.*
FROM (
SELECT matter, activity, completion, date_end
FROM activities
WHERE
matter LIKE '%JR16116'
AND activity = '1.1'
AND DATEDIFF(CURDATE(), date_end) <120
) a1
JOIN (
SELECT matter, activity, completion, date_end
FROM activities
WHERE
matter LIKE '%JR16116'
AND activity = '1.2'
AND DATEDIFF(CURDATE(), date_end) <120
) a2
ON a1.matter = a2.matter
<强> SQL Fiddle 强>:
| matter | activity | completion | date_end | matter | activity | completion | date_end |
|---------|----------|------------|------------|---------|----------|------------|------------|
| JR16116 | 1.1 | 1 | 2017-04-22 | JR16116 | 1.2 | 1 | 2017-04-23 |
查询2 :
-- other way without sub request but clean join
SELECT
a.matter, a.activity, a.completion, a.date_end
,a2.activity, a2.completion, a2.date_end
-- ,a3.activity, a3.completion, a3.date_end
FROM activities a
JOIN activities a2
ON (
a.matter = a2.matter
AND a2.activity = '1.2'
AND DATEDIFF(CURDATE(), a2.date_end) <120
)
-- JOIN activities a3
-- ON (
-- a.matter = a3.matter
-- AND a3.activity = '1.3'
-- AND DATEDIFF(CURDATE(), a3.date_end) <120
-- )
WHERE
a.matter LIKE '%JR16116'
AND a.activity = '1.1'
AND DATEDIFF(CURDATE(), a.date_end) <120
<强> Results 强>:
| matter | activity | completion | date_end | activity | completion | date_end |
|---------|----------|------------|------------|----------|------------|------------|
| JR16116 | 1.1 | 1 | 2017-04-22 | 1.2 | 1 | 2017-04-23 |