我正在尝试创建一个查询,该查询返回typeID为1的所有商品的总数和所有类型ID为2的商品以及typeID为3的所有商品
我不确定我是否在正确的路线上,但我已经想出了这个
SELECT a.Atotal, b.Btotal, c.Ctotal, u.userID, t.typeID
FROM
(SELECT ul.userID, COUNT( ul.listingID ) AS Atotal
FROM tbl_user_listing AS ul
LEFT JOIN tbl_listing_type AS t ON ul.listingID = t.listingID
WHERE t.typeID =1
GROUP BY ul.userID
)AS a,
(SELECT ul.userID, COUNT( ul.listingID ) AS Btotal
FROM tbl_user_listing AS ul
LEFT JOIN tbl_listing_type AS t ON ul.listingID = t.listingID
WHERE t.typeID =2
GROUP BY ul.userID
)AS b,
(SELECT ul.userID, COUNT( ul.listingID ) AS Ctotal
FROM tbl_user_listing AS ul
LEFT JOIN tbl_listing_type AS t ON ul.listingID = t.listingID
WHERE t.typeID =3
GROUP BY ul.userID
)AS c,
FROM tbl_users AS u
WHERE u.userID =1
毫不奇怪,它在第21行引发了例外
它说#1064你的mysql语法中有错误检查手册blah de blah near' FROM tbl_users AS u WHERE u.userID = 1' AT LINE 21
有人可以帮我理解我哪里出错了,如果这是达到我想要的结果的最佳方法 非常感谢答案 0 :(得分:1)
您错过了子查询之间的JOIN
语句。此外,您不能拥有两个FROM
条款。并且你错过了加入条件。
SELECT a.Atotal, b.Btotal, c.Ctotal, u.userID, t.typeID
FROM users AS u
JOIN (SELECT ul.userID, COUNT( ul.listingID ) AS Atotal
FROM tbl_user_listing AS ul
LEFT JOIN tbl_listing_type AS t ON ul.listingID = t.listingID
WHERE t.typeID =1
GROUP BY ul.userID
)AS a ON u.userID = a.userID
JOIN (SELECT ul.userID, COUNT( ul.listingID ) AS Btotal
FROM tbl_user_listing AS ul
LEFT JOIN tbl_listing_type AS t ON ul.listingID = t.listingID
WHERE t.typeID =2
GROUP BY ul.userID
)AS b ON u.userID = b.userID
JOIN (SELECT ul.userID, COUNT( ul.listingID ) AS Ctotal
FROM tbl_user_listing AS ul
LEFT JOIN tbl_listing_type AS t ON ul.listingID = t.listingID
WHERE t.typeID =1
GROUP BY ul.userID
)AS c ON u.userID = c.userID
WHERE u.userID =1
但是,最好将子查询合并为一个查询:
SELECT SUM(t.typeID = 1) AS Atotal, SUM(t.typeID = 2) AS Btotal, SUM(t.typeID = 3) AS Ctotal,
u.userID, t.typeID
FROM users AS u
JOIN tbl_user_listing AS ul ON ul.userID = u.userID
LEFT JOIN tbl_listing_type AS t ON ul.listingID = t.listingID
WHERE u.userID = 1
我猜测t.typeID = 1
是原始c
子查询中的拼写错误。