MySQL查询查询并根据第一个Query和COUNT的WHERE语句返回COUNT

时间:2013-11-13 20:23:24

标签: mysql

必须到桌子。 主人和客人。

HOST表看起来像这样。

* hid (INT, Primary Key, Auto-Increment)
* firstname (VARCHAR)
* lastname (VARCHAR)
* email (VARCHAR)
* registered (DATETIME)
* confirmed (DATETIME)

GUESTS 表格如下:

* gid (INT, Primary Key, Auto-Increment)
* hid (INT)
* firstname (VARCHAR)
* lastname (VARCHAR)
* email (VARCHAR)
* registered (DATETIME)
* confirmed (DATETIME)

期望的结果是输出具有HOSTS的行和 COUNT 他们拥有多少GUESTS CONFIRMED 日期和时间之前 / strong> 2013-11-10 14:00:00 两者 HOSTS和GUESTS。

之前收到了答案但没有 WHERE 语句,看起来像这样:

SELECT   HOSTS.*, COUNT(gid)
FROM     HOSTS LEFT JOIN GUESTS USING (hid)
GROUP BY hid

对于HOSTS和GUESTS,查询应如何包含之前 2013-11-10 14:00:00?

1 个答案:

答案 0 :(得分:0)

使用以下条件,我不确定MYSQL的确切语法但是尝试这种方式,这是在DB2中,您可能需要更改子查询中的WHERE条件

SELECT *H.*, J.CNT_GID
FROM HOSTS AS H
INNER JOIN
(
SELECT G.HID, COUNT(GID) AS CNT_GID
FROM GUESTS AS G
WHERE GUESTS.CONFIRMED < DATE('2013-11-10 14:00:00') #you may need to change here
GROUP BY G.HID
) AS J
ON H.HID = J.HID