我有4个表,以及如何在查询结果时创建。
表格卡
id name
1 card1
2 card2
3 card3
4 card4
表格访问
id card_id
1 1
2 1
3 1
4 1
5 2
6 2
7 3
8 4
表格喜欢
id card_id
1 1
2 2
3 2
4 2
5 3
6 3
7 3
8 4
表最喜欢的
id card_id
1 1
2 1
3 1
4 1
5 3
6 3
7 3
8 4
结果
name visit like favorite
card1 4 1 4
card2 2 3 0
card3 1 3 3
card4 1 1 1
答案 0 :(得分:1)
SELECT C.Name,
(SELECT COUNT(*) FROM VISIT AS V WHERE V.Card_Id = C.Id) AS Visits,
(SELECT COUNT(*) FROM `LIKE` AS L WHERE L.Card_Id = C.Id) AS Likes,
(SELECT COUNT(*) FROM FAVORITE AS F WHERE F.Card_Id = C.Id) AS Favorite
FROM Card AS C
答案 1 :(得分:1)
我会使用此查询:
SELECT
card.name,
SUM(visit) AS visit,
SUM(`like`) AS `like`,
SUM(favorite) AS favorite
FROM
card INNER JOIN
(
SELECT card_id, COUNT(*) as visit, 0 as `like`, 0 as favorite
FROM visit
GROUP BY card_id
UNION ALL
SELECT card_id, 0 as visit, COUNT(*) as `like`, 0 as favorite
FROM `like`
GROUP BY card_id
UNION ALL
SELECT card_id, 0 as visit, 0 as `like`, COUNT(*) as favorite
FROM favorite
GROUP BY card_id
) counts ON card.id = counts.card_id
GROUP BY card.id, card.name