组合来自同一个表的两个选择查询

时间:2018-03-21 17:37:06

标签: mysql

我需要做这样的事情:

id  tag  status user   trial   Value (other columns)... 
1   A    Pass   peter  first   0
2   A    Pass   peter  second  1
3   A    Fail   peter  third   3
4   B    Pass   peter  first   4
5   B    Pass   peter  second  5
6   B    Pass   peter  third   6

选择标记为A且状态等于Pass的行,并为其他标记ex找到相同的值:B

id  tag  status user   trial   Value_tag_A  Value_tag_B  (other columns)... 
1   A    Pass   peter  first   O            4
2   A    Pass   peter  second  1            5

我可以使用php进行一些处理以获得此结果,但我想知道我是否可以直接使用sql

我尝试了很多变化,似乎无法接近结果。

解决方案:http://sqlfiddle.com/#!9/e9068d/17

1 个答案:

答案 0 :(得分:0)

我不知道为什么tag=A也有Value_tag_B的行。我会忽略这一点,也许以下查询是一种方法。

SELECT DISTINCT y.status, y.`user`, y.trial, 
(SELECT Value FROM toto WHERE y.`user` = `user` and y.trial = trial and tag = 'A' ) AS Value_tag_A,
(SELECT Value FROM toto WHERE y.`user` = `user` and y.trial = trial and tag = 'B' ) AS Value_tag_B
FROM toto y
WHERE y.trial NOT IN (SELECT DISTINCT trial FROM toto WHERE `status` <> 'Pass')

代码已被修改。

SQL Fiddle