简体   繁体   English

MySQL查询使用来自单独表的信息

[英]MySQL query using info from seperate tables

I have a rather complex SQL query that I am looking for a little help with. 我有一个相当复杂的SQL查询,我正在寻找一些帮助。

I have two tables: a history table and a details table. 我有两个表:历史表和详细信息表。

The history table contains the following columns. 历史记录表包含以下列。

Event Date(ev_date) 
Event Code(ev_code)  
Machine ID(mc_id)

The Details table contains the following columns: “详细信息”表包含以下列:

Machine ID(mc_id), 
Location ID(lo_id) 
Machine Name(mc_name)

I need a query that returns the count of the number of events from the history table between a given date range of a given group of machines given by Location ID. 我需要一个查询,它返回位置ID给定的给定计算机组的给定日期范围之间历史表中事件数的计数。

So, kinda in sudo code: 所以,在sudo代码中有点:

SELECT COUNT(*) 
FROM history 
WHERE ev_date (BETWEEN start_date AND end_date) AND ev_code = 1 AND ???? 

(mc_id must have certain lo_id from details table). (mc_id必须具有来自详细信息表的某些lo_id)。

Does this make sense? 这有意义吗?

Thanks 谢谢

SELECT COUNT(*)
    FROM history h
    WHERE h.ev_date BETWEEN @start_date AND @end_date
        AND ev_code = 1
        AND EXISTS(SELECT NULL
                       FROM details d
                       WHERE h.mc_id = d.mc_id
                           AND d.lo_id = @LocationID);

Assuming you have a one-to-one mapping between history and details on mc_id : 假设您在mc_id historydetails之间的一对一映射:

SELECT COUNT(*)
FROM history h
JOIN details d USING mc_id
WHERE h.ev_code = 1
AND h.ev_date between start_date and end_date
AND d.lo_id IN (?, ?, ?, ...)

Alternatively ON h.mc_id = d.mc_id instead of USING mc_id . 或者ON h.mc_id = d.mc_id而不是USING mc_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM