mysql select 存在与否

mysql select in case of existing or not

我正在尝试编写 SELECT 语句,其中 return 某些元素 + 当前时间与 date_created 或 date_edited 之间的日期差异。如果字段被编辑,我应该从编辑元素后更新的其他 table 中获取 date_edited,如果不是,我应该从当前元素中获取 date_created,因为该元素与其他编辑元素没有关系元素 table,并计算 DATEDIFF(NOW(), date_created/date_edited)。我写了 select ,它给我带来了正确日期的编辑元素,而其他 select 带来了所有元素,就像它们被编辑一样,它给我带来了不正确的日期差异。所以总而言之,我需要形成一个 table,它给我带来计算日期差异的元素。

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;

这个给了我所有的元素,但如果它们被编辑过,当然会有错误的日期差异。需要以某种方式组合这些 select 并形成单个 table。 提前致谢!

我想你可以用 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;

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

您可以离开加入编辑 table 并在日期字段上放置一个 ISNULL()IFNULL() in 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;

Left/Outer 加入 tables 是在 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;

http://www.w3schools.com/sql/sql_union.asp