仅查找一条记录的分组查询(employee_id = 1或null)

时间:2018-05-27 19:06:25

标签: mysql sql

我的数据库信息是
 enter image description here

如果employee_id具有该记录的值,则不会获取每个工作日的唯一记录,否则employee_id为Null。 我试试这个查询

SELECT 
  * 
FROM
  `calendar` 
WHERE `employee_id` = 1 
  OR `employee_id` IS NULL 
GROUP BY `weekday` 

结果是

enter image description here

但我希望

enter image description here

你能帮帮我吗?感谢

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT 
  b.calendar_id,
  a.employee_id,
  a.weekday 
FROM
  (SELECT 
    `weekday`,
    MAX(employee_id) AS employee_id 
  FROM
    calendar 
  WHERE employee_id = 1 
    OR employee_id IS NULL 
  GROUP BY `weekday`) a 
  LEFT JOIN calendar b 
    ON a.weekday = b.weekday 
    AND a.employee_id = b.employee_id ;

如有任何澄清,请通知我。

答案 1 :(得分:0)

问题是,<form asp-action="ActivityCreateSubmit"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Id" class="control-label"></label> <input asp-for="Id" class="form-control" /> <span asp-validation-for="Id" class="text-danger"></span> </div> <div class="form-group" style="display: none;"> <label asp-for="Name" class="control-label"></label> <input asp-for="Name" class="form-control" value="@ViewBag.AppId" /> <span asp-validation-for="Name" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="MyType" class="control-label"></label> <select id="selection" asp-for="MyType" asp-items="Html.GetEnumSelectList<MyType>()"> <option value="">Select...</option> </select> <span asp-validation-for="MyType" class="text-danger"></span> </div> @switch(Model.MyType) { case FirstConfig: <input name="first-input" /> <input name="second-input" /> <input name="third-input" /> break; case SecondConfig: ... Do something ... break; } <div class="form-group"> <input type="submit" value="Create" class="btn btn-default" /> </div> </form> 之后列表中的列没有出现在//Ignore ActivityTable, it is a dependency injection. public ActionResult ActivityCreateSubmit(ActivityTable at, MyModel a) { at.AddActivity(a) return View("../Home/Index"); } //This is the page I am working on creating public ActionResult ActivityCreate() { return (View()); } 表达式中,也没有应用聚合函数。与大多数其他DBMS相比,MySQL在旧版本(或某些设置)中允许这样做,但结果很可能是垃圾。

通过在SELECT表达式中包含列或对它们应用聚合函数来解决此问题。例如:

GROUP BY

请注意GROUP BY上的SELECT max(`employee_id`), `weekday` FROM `calendar` WHERE `employee_id` = 1 OR `employee_id` IS NULL GROUP BY `weekday`; 汇总功能。