所以我试图在屏幕上显示一些包含计数的数据。计数由两个字段startingAT和endingAt计算。
SELECT * FROM venue
INNER JOIN plans ON venue.idVenue=plans.endingAt OR venue.idVenue=plans.startingAt
WHERE venue.idLocation = 3
这是我当前的查询。我想添加计数,但我正在努力的地方是起点和终点在计划表中。所以我的问题是如何从联合表中计算,我如何计算两个字段?
提前谢谢!
答案 0 :(得分:1)
如果你想计算其中一个匹配的位置。你可以这样做:
SELECT
SUM(CASE
WHEN venue.idVenue=plans.endingAt
OR venue.idVenue=plans.startingAt
THEN 1
ELSE 0
END
) AS NumberOf
FROM venue
INNER JOIN plans
ON venue.idVenue=plans.endingAt OR venue.idVenue=plans.startingAt
WHERE
venue.idLocation = 3
这将为您提供总计数。如果您想知道每个idVenue,您可以通过这样的组来完成:
SELECT
SUM(CASE
WHEN venue.idVenue=plans.endingAt
OR venue.idVenue=plans.startingAt
THEN 1
ELSE 0
END
) AS NumberOf,
venue.idVenue
FROM venue
INNER JOIN plans ON venue.idVenue=plans.endingAt
OR venue.idVenue=plans.startingAt
WHERE
venue.idLocation = 3
GROUP BY
venue.idVenue
或者,如果您只想计算并将所有字段组成场地表。你可以这样做:
SELECT
(
SELECT
COUNT(*)
FROM
plans
WHERE
venue.idVenue=plans.endingAt OR venue.idVenue=plans.startingAt
) AS numberOf,
venue.*
FROM
venue
WHERE
venue.idLocation = 3
更新: 然后,如果要按列排序,则需要在列上添加别名。像这样:
SELECT
*
FROM
(
SELECT
(
SELECT
COUNT(*)
FROM
plans
WHERE
venue.idVenue=plans.endingAt OR venue.idVenue=plans.startingAt
) AS numberOf,
venue.*
FROM
venue
WHERE
venue.idLocation = 3
) AS tbl
ORDER BY tbl.numberOf