在MYSQL中查看3个表

cam*_*oto -1 mysql sql view

我在mysql中有3个表

table 1
date        name   total recieve
2013-05-09  "aa"    20    15
2013-05-09  "bb"    10    17

table 2
name    tree
"bb"     "a1"
"aa"     "a2"

table 3
date          tree      users
2013-05-09   "a1SI"      19
2013-05-09   "a1NO"      24
2013-05-09   "a2SI"      39
2013-05-09   "a2NO"      22
Run Code Online (Sandbox Code Playgroud)

我需要一个树表的视图

这是我需要的观点:

date         name   tree   total    recieve    userSI    userNO  
2013-05-09   "aa"   "a2"    20        15        39         22
2013-05-09   "bb"   "a1"    10        17        19         24
Run Code Online (Sandbox Code Playgroud)

我有一半的查询

SELECT t1.`date` , t1.`name` , t2.`tree` , t1.`total` , t1.`recieve`,
FROM  `table1` t1
INNER JOIN  `table2` t2 ON t1.`name` = t2.`name` 
ORDER BY  `t1`.`date` DESC
Run Code Online (Sandbox Code Playgroud)

但我不知道三个表和其他问题的视图是如何树的记录,因为我有树"a1"和"a1Si"和"a2NO",在视图中我需要关联3列

Tar*_*ryn 10

你应该能够使用它连接下面table3t2.tree和的左边两个字符t3.tree:

SELECT t1.`date` , t1.`name` , t2.`tree` , t1.`total` , t1.`recieve`,
  max(case when right(t3.tree, 2) = 'SI' then t3.users end) usersSI,
  max(case when right(t3.tree, 2) = 'NO' then t3.users end) usersNO
FROM  `table1` t1
INNER JOIN  `table2` t2 
  ON t1.`name` = t2.`name` 
INNER JOIN `table3` t3
  on t2.tree = left(t3.tree, 2)
group by t1.`date` , t1.`name` , t2.`tree` , t1.`total` , t1.`recieve`
ORDER BY  `t1`.`date` DESC;
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo.

这也可以使用多个JOIN来完成table3:

SELECT t1.`date` , t1.`name` , t2.`tree` , t1.`total` , t1.`recieve`,
  t3SI.users usersSI,
  t3NO.users usersNO
FROM  `table1` t1
INNER JOIN  `table2` t2 
  ON t1.`name` = t2.`name` 
LEFT JOIN `table3` t3SI
  on t2.tree = left(t3SI.tree, 2)
  and right(t3SI.tree, 2) = 'SI'
LEFT JOIN `table3` t3NO
  on t2.tree = left(t3NO.tree, 2)
  and right(t3NO.tree, 2) = 'NO'
ORDER BY  `t1`.`date` DESC;
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo.你会注意到我改变了最后两个连接,以便LEFT JOIN在没有匹配SIor 的树的情况下使用a NO,然后你将返回数据.如果您知道您将拥有匹配的数据,那么您可以使用INNER JOIN.

如果你有更长的树名,那么你可以在JOIN中实现LIKE子句:

SELECT t1.`date` , t1.`name` , t2.`tree` , t1.`total` , t1.`recieve`,
  t3SI.users usersSI,
  t3NO.users usersNO
FROM  `table1` t1
INNER JOIN  `table2` t2 
  ON t1.`name` = t2.`name` 
LEFT JOIN `table3` t3SI
  on t3SI.tree like concat(t2.tree, '%')
  and right(t3SI.tree, 2) = 'SI'
LEFT JOIN `table3` t3NO
  on t3NO.tree like concat(t2.tree, '%')
  and right(t3NO.tree, 2) = 'NO'
ORDER BY  `t1`.`date` DESC;
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo

  • @BenitoCamelas您应该在原始帖子中包含所有必要的详细信息.您还可以尝试在JOIN中使用LIKE子句. (2认同)
  • @bluefeet对于意外向下投票(以及随后的奇怪编辑以解锁它)感到抱歉.我必须在没有意识到的情况下疯狂地点击.现在改为投票! (2认同)