我在MySQL數據庫中的表2:獲取數和總數在mysql中加入2個表
1.
p_code{
code varchar(10) primary key,
discount decimal(4,2) not null,
valid_till date not null,
daily int not null,
total int non null,
max_amount decimal (6, 2) not null
}
2.
p_user{
code varchar(10) not null,
email varchar(50) not null,
date date not null,
primary key (code, email, date),
foreign key (code) references p_code(code)
}
現在我想對於總共使用email
多少次,總共使用多少次email
以及的細節。
我曾嘗試以下查詢:
SELECT pc.discount, pc.valid, pc.daily, pc.total, pc.max_amount, c.tcount, c.count
FROM p_code AS pc
LEFT JOIN (
SELECT t.code, t.email, t.tcount, p.count
FROM (
SELECT code, email, COUNT(email) AS tcount
FROM p_user
GROUP BY code, email
) AS t
LEFT JOIN (
SELECT code, email, COUNT(email) AS count
FROM p_user
WHERE `date` = CURDATE()
GROUP BY code, email
) AS p ON (t.code, t.email) = (p.code, p.email)
) AS c ON pc.code = c.code
WHERE c.email = ?
AND pc.code = ?
但問題是,如果我沒有在表中p_user
爲code
和email
中的任何條目,它不返回任何行。
我要求它應該返回p_code
的所有列以及tcount
和count
列的0和0。
當LEFT JOIN,出右側表的ON子句中的條件,以獲得真正的左聯接行爲。 (在WHERE中,你會得到經常的內部連接結果。) – jarlh
@jarlh你是說我應該刪除'where c.email =?'?我要刪除它,我應該把它放在哪裏才能得到給定的'email'的結果? – Blip
將'c.email =?'移動到'ON'子句,即'... AS c ON pc.code = c.code AND c.email =?在哪裏pc.code =?'。 – jarlh