我如何在一个表中使用多个WHERE进行SELECT

时间:2017-07-05 20:21:24

标签: mysql

我在数据库中有行表:

idkillsdeathsweek

我如何选择kills week=1deaths哪里week=2在一个表中?

2 个答案:

答案 0 :(得分:3)

您可以使用两个单独的select语句:

SELECT(
    (SELECT kills FROM tablename WHERE week = 1),
    (SELECT deaths FROM tablename WHERE week = 2)
)

这将为周期= 1的杀戮创建一列,为周= 2的死亡创建另一列。

您可以使用UNION关键字将它们组合在一起:

SELECT 'week 1 - kills' as source, kills FROM tablename WHERE week = 1
UNION
SELECT 'week 2 - deaths' as source, deaths FROM tablename WHERE week = 2

这两种方法需要对表进行双重扫描。

如果您需要聚合函数,另一种方法是使用条件子句@Juan Carlos Oropeza的解决方案。但是,正如所指出的那样,将这两个陈述合并为一个可能不是最佳选择。

答案 1 :(得分:2)

您可以使用条件聚合

SELECT SUM (CASE WHEN week = 1 THEN kills END) as total_kills_week1, 
       SUM (CASE WHEN week = 2 THEN deaths END) as total_deaths_week2
FROM YourTable