我正在尝试编写SELECT语句,它将返回一些元素+当前时间与date_created或date_edited之间的日期差异。如果字段被编辑,我应该从编辑元素后更新的其他表中获取date_edited,如果不是,我应该从当前的一个获取date_created,因为该元素与其他已编辑的元素表没有关系,并计算DATEDIFF(NOW(),date_created / date_edited)。我写了选择,它给我带来了正确日期的编辑元素,而其他选项带来了所有元素,如果它们被编辑它会给我带来不正确的日期差异。总而言之,我需要形成单个表格,它为我带来了计算日期差异的元素。
SELECT
table1.name,
table1.sales_stage,
users.user_name,
DATEDIFF(NOW(), table1_edit.date_edited) as DaysOnStage
FROM table1
join users on table1.assigned_user_id = users.id
join table1_edit on table1.id = table1_edit.parent_id
WHERE table1.sales_stage = table1_edit.after_value_string;
这个带来了所有编辑过的值,并计算了正确的日期。
SELECT
table1.name,
table1.sales_stage,
users.user_name,
DATEDIFF(NOW(), table1.date_created) as DaysOnStage
FROM table1
join users on table1.assigned_user_id = users.id;
这个给我带来了所有的元素,但是如果他们被编辑的话,日期差异很大。需要以某种方式结合这些选择并形成单个表。 提前致谢!
答案 0 :(得分:0)
我认为您可以使用left join
执行所需操作,然后使用COALESCE()
选择正确的值:
SELECT t1.name, t1.sales_stage, u.user_name,
DATEDIFF(NOW(), COALESCE(te.date_edited, t1.date_created)) as DaysOnStage
FROM table1 t1 join
users u
on t1.assigned_user_id = u.id LEFT JOIN
table1_edit te
on t1.id = te.parent_id
WHERE t1.sales_stage = te.after_value_string;
答案 1 :(得分:0)
if应该有所帮助
SELECT
table1.name,
table1.sales_stage,
users.user_name,
if (table1_edit.parent_id is null, DATEDIFF(NOW(), table1_edit.date_edited), DATEDIFF(NOW(), table1.date_created)) as DaysOnStage
FROM table1
join users on table1.assigned_user_id = users.id
left join table1_edit on table1.id = table1_edit.parent_id
enter code here
答案 2 :(得分:0)
您可以离开加入编辑表并在日期字段中放置ISNULL()
(IFNULL()
在mysql中)函数:
SELECT
table1.name,
table1.sales_stage,
users.user_name,
DATEDIFF(NOW(), IFNULL(table1_edit.date_edited,table1.date_created) as DaysOnStage
FROM table1
join users on table1.assigned_user_id = users.id
left join table1_edit on table1.id = table1_edit.parent_id
WHERE table1.sales_stage = table1_edit.after_value_string;
左/外连接表是在SQL中工作的必修课: http://www.w3schools.com/sql/sql_join_left.asp
或者您可以在查询中使用UNION:
SELECT
table1.name,
table1.sales_stage,
users.user_name,
DATEDIFF(NOW(), table1_edit.date_edited) as DaysOnStage
FROM table1
join users on table1.assigned_user_id = users.id
join table1_edit on table1.id = table1_edit.parent_id
WHERE table1.sales_stage = table1_edit.after_value_string;
This one brings all edited values with correct date calculated.
UNION
SELECT
table1.name,
table1.sales_stage,
users.user_name,
DATEDIFF(NOW(), table1.date_created) as DaysOnStage
FROM table1
join users on table1.assigned_user_id = users.id;