mysql - 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 逻辑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'
推荐阅读
- python - 当我在 python 中使用 logging.config.fileConfig('log.conf') 时,它会抛出一个错误:ModuleNotFoundError: No module named 'handlers'
- ibm-midrange - 如何使用 SQLTYPE(CLOB_File) 替换流文件中的整行文本?
- c# - 从集合 vew 单元格中的选定单元格获取数据
- powershell - 无法将 Powershell 脚本发布到库
- javascript - Webpack 5 Terser:我如何需要'uglify-module'
- vim - 在函数内部复制vim中的映射
- python - 创建一个函数,在数据框中迭代日期以搜索最新的值,然后将它们保存到新的数据框中
- c# - ASP.NET 核心 - 配置文件未映射到 POCO
- python - NotImplementedError:此表达式不支持运算符“getitem”
- javascript - 如何使此随机图像生成器功能成为页面的背景图像?