我的表像這樣在我的數據庫JOIN許多表,而GROUP BY和COUNT在GROUP BY行的MySQL
lp_kon
ID | lpkonName
1 | kon1
2 | kon2
lp_seb
ID | ID_lpkon | lpsebName
1 | 1 | seb1
2 | 2 | seb3
lp_rek
ID | ID_lpseb | lprekName
1 | 1 | rek1
2 | 1 | rek2
lp_tl
ID | ID_lprek | lptlName
1 | 1 | tl1
2 | 1 | tl2
我用這個查詢加入這些4桌
SELECT
a.id as id_lpkon,
b.id as id_seb,
c.id as id_rek,
d.id as id_tl
FROM `lp_kon` a
left OUTER JOIN lp_seb b ON a.id = b.ID_lpkon
LEFT OUTER join lp_rek c on b.id = c.ID_lpseb
LEFT OUTER join lp_tl d on c.id = d.ID_lprek
ORDER by a.id ASC
我喜歡這個
id_lpkon|id_lpseb|id_lprek|id_lptl|
1 | 1 | 1 | 1 |
1 | 1 | 1 | 2 |
1 | 1 | 2 | NULL |
1 | 2 | NULL | NULL |
2 | Null | NULL | NUll |
我如何算一個resut錶行,而分組。像下面
id_lpkon | count(lpkon) | id_seb | count(lpseb | id_rek | count(lprek) | id_lptl | count(lptl)
1 | 4 | 1 | 3 | 1 | 2 |1 | 1 |
1 | 4 | 1 | 3 | 1 | 2 |2 | 1 |
1 | 4 | 1 | 3 | 2 | 1 |NUll |NUll |
1 | 4 | 2 | 1 | NULL | NULL |NULL |NULL |
2 | 1 | NULL | NULL | NULL | NULL |NULL |
SO每一行的結果,他們有一個數列的每個關係表
更新與查詢
Lp_kon
CREATE TABLE `lp_kon` (`ID` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `lpkonName` text NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1
INSERT INTO `lp_kon` (`ID`, `lpkonName`) VALUES (NULL, 'kon1'), (NULL, 'kon2');
Lp_seb
CREATE TABLE `lp_seb` (`ID` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,`ID_lpkon` text NOT NULL, `lpsebName` text NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1
INSERT INTO `lp_seb` (`ID`,`ID_lpkon`, `lpsebName`) VALUES (NULL,`1`,'seb1'), (NULL,`2`,'seb3');
Lp_rek
CREATE TABLE `lp_rek` (`ID` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,`ID_lpseb` text NOT NULL, `lprekName` text NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1
INSERT INTO `lp_rek` (`ID`,`ID_lpkon`, `lprekName`) VALUES (NULL,`1`,'rek1'), (NULL,`1`,'rek2');
Lp_tl
CREATE TABLE `lp_tl` (`ID` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,`ID_lprek` text NOT NULL, `lptlName` text NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1
INSERT INTO `lp_tl` (`ID`,`ID_lprek`, `lpsebName`) VALUES (NULL,`1`,'tl1'), (NULL,`1`,'tl2');
如果你的意思是分別統計他們,我看到'和()'作爲一個答案,但如果你想單獨的罪名,你應該這樣做一系列相關子查詢而不是連接,將它關聯到外鍵上(這可能會起作用)你必須明白count是一個「聚合」函數,並且通常會返回1行,除非使用group by。 – ArtisticPhoenix
這是一個相當好的例子,但它不會很容易(有很多表格)https://stackoverflow.com/questions/17105523/sql-add-rows-count-from-a-second-table-to-the -main-query將它們分開可能會更好,我在工作時正在處理一個查詢,結果是9個連接,3個聯合和4個子查詢,我想我會在星期一分別完成它們......大聲笑 – ArtisticPhoenix
謝謝!爲refference https://stackoverflow.com/questions/17105523/sql-add-rows-count-from-a-second-table-to-the-main-query 這就是我要找的@ArtisticPhoenix – Gagantous