简体   繁体   English

MySQL简单嵌套选择语句

[英]MySQL Simple Nested Select Statement

I have one table reports, which contains all info and read reports which just has Report ID and ID (of owner of the report) 我有一个表格报告,其中包含所有信息和阅读报告,这些报告只有报告ID和ID(报告的所有者)

I'm trying to do this statment (correct me if theres better out there) so it gets all the reports ID from read reports which match ID 1, and pick out all the details from reports for it. 我正在尝试做这个声明(如果那里有更好的话,请更正我),这样它就可以从与ID 1匹配的阅读报告中获取所有报告ID,并从报告中选择所有详细信息。 (Report ID's are the same on reports and read reports) (报告ID和报告上的报告ID相同)

But this statement is giving me back no rows: 但是这句话让我没有回头:

SELECT a.* 
 FROM `Reports` AS a, 
      (SELECT `Report ID` FROM `Read Reports` WHERE `Id` = 1) AS b
      WHERE a.`Report ID` = b.`Report ID`;

Whats wrong with it/how can I improve it? 它有什么问题/我该如何改善?

Thanks, 谢谢,

EDIT: My bad, it works fine!! 编辑:我不好,它工作正常! Id 1 had no reports. ID 1没有报告。 Close this. 关闭这个。 :L :L

EDIT2: Still post if you have improvements though :P EDIT2:如果您有所改进,仍然发布:P

Try this: 尝试这个:

SELECT a.*, (SELECT `Report ID` FROM `Read Reports` WHERE `Id` = 1) AS b_report_id
FROM `Reports` AS a
HAVING a.`Report ID` = b_report_id;

There seems to be nothing wrong with your query and it should return the records unless there are no matching records. 您的查询似乎没有任何问题,它应该返回记录,除非没有匹配的记录。 But if you say that there do exist matching records, I'd suggest that you re-read your query to confirm that you are using the right column names, ie not replaced "Id" with "Report ID"? 但是,如果你说确实存在匹配的记录,我建议你重新阅读你的查询以确认你使用了正确的列名,即没有用“报告ID”替换“Id”?

Can you give a snapshot of your data in your post? 您可以在帖子中提供数据快照吗?

By the way, the below query should be better because it does not involve derived table: 顺便说一句,下面的查询应该更好,因为它不涉及派生表:

SELECT `a`.*
FROM `Reports` AS `a`
INNER JOIN `Read Reports` AS `b` ON `a`.`Report ID` = `b`.`Report ID`
WHERE `b`.`Id` = 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM