我有一个成员表,其中包含各种其他表的外键。我正在检查这些表中的每一个,以查看成员中是否有一个或多个记录,如果是,我返回一个值,如果不是,我返回0,这全部被选为总计。这主要是在一个地方工作。我需要检查两个表,如果其中任何一个都有记录,则查询将返回5,0否则。我试图使用UNION计数的SUM,但是我没有得到我期望的结果,似乎只选择了两个表中每个表中的第一个记录,就是这样。
我正在使用(经过一些帮助)一系列相关查询与COUNT()和IF()来获得总数。以下是查询的部分内容:
SELECT
member_id,
(SELECT IF(COUNT(member_id)>0,10,0) FROM tbl1 WHERE member_id = m.member_id)
+
(SELECT IF(SUM(tbl_count) > 0,5,0) FROM
(
SELECT member_id, COUNT(tbl2.id) as tbl_count
FROM tbl2
UNION ALL
SELECT member_id, COUNT(tbl3.id) as tbl_count
FROM tbl3
) sub WHERE sub.member_id = m.member_id
)
as total
FROM members m
实际查询连接另外10个左右的表,同样唯一不起作用的部分是带UNION的COUNT的SUM。谁能建议我该怎么做?任何帮助将非常感谢。非常感谢你。
答案 0 :(得分:2)
我认为你正在寻找这个:
首先尝试(失败)
SELECT
member_id,
(SELECT IF(COUNT(member_id)>0,10,0) FROM tbl1 WHERE member_id = m.member_id)
+
(SELECT IF(SUM(tbl_count) > 0,5,0) FROM
(
SELECT COUNT(*) as tbl_count
FROM tbl2
WHERE tbl2.member_id = m.member_id
UNION ALL
SELECT COUNT(*) as tbl_count
FROM tbl3
WHERE tbl3.member_id = m.member_id
) sub
)
as total
FROM members m
第二次尝试:
SELECT
member_id,
(SELECT IF(COUNT(member_id)>0,10,0) FROM tbl1 WHERE member_id = m.member_id)
+
(SELECT IF(SUM(tbl_count) > 0,5,0) FROM
(
SELECT member_id, COUNT(*) as tbl_count
FROM tbl2
GROUP BY member_id
UNION ALL
SELECT member_id, COUNT(*) as tbl_count
FROM tbl3
GROUP BY member_id
) sub
WHERE sub.member_id = m.member_id
)
as total
FROM members m
如果查询有10个连接,你可能需要考虑重构...: - )