首页 > 解决方案 > MySQL 根据结果将结果添加到查询中

问题描述

我知道标题含糊不清,这对我来说可能很难解释,但这就是我想要完成的。

假设我有一个名为文章的表。

在那个表中,我有一个 ID、密码、文件、组等......

我想做一个密码='thispassword'的查询。很容易。

但是然后以某种方式加入该查询的结果还包括 where group=file

id | password  | file   | group
----------------------------------
1  | passA     | 1filea | group1
2  | passB     | 2fileb | group1
3  |           | group1 | 
4  | passD     | 4filed | group2
5  | passD     | 5filee | group2
6  |           | group2 | 

使用上面的表格,如果我查询 passA (WHERE password='passA') 它在 group 列中有group1 。我还想在同一个查询中返回文件等于 group1 的位置,即上表中的 id: 3。

标签: mysql

解决方案


看起来我们可以使用 MySQL 逻辑OR运算符来满足规范。

https://dev.mysql.com/doc/refman/5.7/en/logical-operators.html#operator_or

  FROM mytable t
 WHERE t.password = 'passA' 
    OR t.file     = 'group1'

给定样本数据,我们希望这会返回两行,id 值 1 和 3。

规范并不完全清楚。我们可以结合多个条件得到不同的结果:

  FROM mytable t
 WHERE ( t.password IN ('passA','') OR t.password IS NULL )
   AND t.file     = 'group1'

编辑

如果我理解规范,则列中的值是该group列的外键file

SELECT t.id
     , t.password
     , t.file
     , t.group
  FROM mytable t
 WHERE t.password = 'passA'

 UNION ALL

SELECT f.id
     , f.password
     , f.file
     , f.group
  FROM mytable g
  JOIN mytable f
    ON f.file = g.group
 WHERE g.password = 'passA'

推荐阅读