Mysql子查询?
我有一个与此类似的报告表
reports
inspection_type | inspection_number
berries | 111
citrus | 222
grapes | 333
inspection_type
在我的例子中是我想要的另一个表的名称 到SELECT *
,其中inspection_number
等于report_key
该关联表。
{fruit}
row | report_key | etc....
value | 111 | value
value | 222 | value
问题是我不知道如何查询 Inspection_type 来获取表名 来查询该值。这有什么意义吗?
我在这里尝试了这个,但即使我知道这是明显错误的:
SELECT inpection_type, inspection_number
FROM reports rpt
ON rpt.inspection_number = report_key
(SELECT * FROM inspection_type WHERE status < '2')
WHERE rpt.status < '2'
ORDER BY rpt.inspection_number DESC
SQL 大师可以告诉我执行此操作的最佳方法吗?
I have a report table that looks similar to this
reports
inspection_type | inspection_number
berries | 111
citrus | 222
grapes | 333
inspection_type
in my case is the name of the other table I would like
to SELECT *
from where the inspection_number
equals report_key
on
that associated table.
{fruit}
row | report_key | etc....
value | 111 | value
value | 222 | value
The issue is I do not know how to query inspection_type to get the table name
to query the value. Does that make any sense?
I tried this here, but even I know that it's glaringly wrong:
SELECT inpection_type, inspection_number
FROM reports rpt
ON rpt.inspection_number = report_key
(SELECT * FROM inspection_type WHERE status < '2')
WHERE rpt.status < '2'
ORDER BY rpt.inspection_number DESC
Could a SQL guru tell me the best way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于不可能直接在 TSQL 中使用表名变量,因此您必须动态构造 TSQL。
存储过程中的变量表名称
Since it is not possible to have a variable for a table name directly in TSQL, you will have to dynamically construct the TSQL.
Variable table names in Stored Procedures
你不能真正只用 SQL 来完成你的目标,你需要用另一种语言搞乱,或者(这是首选解决方案)重组数据库,即(对元代码感到抱歉)
然后你的 上面的简短
概述相当模糊,因为您现有的表数据尚未真正指定,但总体原则是合理的。将数据从现有结构中迁移出来甚至不需要太多时间,但是完成后,它将为您提供更清晰的查询,并允许您更轻松地实际获取所需的数据
You can't really do what you are aiming to in SQL alone, you'll need to either mess around in another language, or (and this is the preferred solution) restructure the database i.e. (sorry for the meta-code)
Then your query would be simply
The brief overview above is quite vague because your existing table data hasn't really been specified, but the general principle is sound. It wouldn't even take much to migrate data out of your existing structure, but when it's done it'll give you far cleaner queries and allow you to actually get the data you're after out more easily