简体   繁体   English

MySQL查询以获得所需的结果

[英]Mysql query to get desired result

I have been working with SQL joins and kinda stuck with following scenario: 我一直在使用SQL联接,并且在以下情况下会遇到问题:

Table 1: PK(ID, GRADE) 表1:PK(ID,GRADE)

| | ID | ID | Grade | 等级| Student_Count | 学生人数|

| | 1 | 1 | 10th | 10 | 20 | 20 |
| | 1 | 1 | 9th | 9号| 20 | 20 |
| | 2 | 2 | 10th | 10 | 20 | 20 |
| | 2 | 2 | 9th | 9号| 20 | 20 |


Table 2:PK(ID, Grade, Visited_Date) 表2:PK(ID,等级,访问日期)

| | ID | ID | Grade | 等级| Visited | 访问过| Visit_Date | Visit_Date |

| | 1 | 1 | 10th | 10 | Yes | 是的 25-Dec-2015 | 2015年12月25日|
| | 1 | 1 | 10th | 10 | No | 没有 26-Dec-2015 | 2015年12月26日|
| | 1 | 1 | 9th | 9号| Yes | 是的 28-Dec-2015 | 2015年12月28日|
| | 1 | 1 | 9th | 9号| No | 没有 29-Dec-2015 | 2015年12月29日|
| | 2 | 2 | 10th | 10 | Yes | 是的 27-Dec-2015 | 2015年12月27日|
| | 2 | 2 | 9th | 9号| No | 没有 30-Dec-2015 | 2015年12月30日|


What i need is a SELECT query which returns data from both the tables for a given ID in such a way that output rows should match the data of the Table 2 (no all possible combinations like cross/dot product) along with non-common columns from Table 1. 我需要的是一个SELECT查询,该查询从两个表中返回给定ID的数据,以使输出行应与表2的数据匹配(没有像十字/点乘积这样的所有可能组合)以及不常见的列从表1。

For example for ID "1" the output should be: 例如,对于ID“ 1”,输出应为:

| | ID | ID | Grade | 等级| Student_Count | 学生人数| Visited | 访问过| Visit_date | Visit_date |

| | 1 | 1 | 10th | 10 | 20 | 20 | Yes | 是的 25-Dec-2015 | 2015年12月25日|

| | 1 | 1 | 10th | 10 | 20 | 20 | No | 没有 26-Dec-2015 | 2015年12月26日|

| | 1 | 1 | 9th | 9号| 20 | 20 | Yes | 是的 28-Dec-2015 | 2015年12月28日|

| | 1 | 1 | 9th | 9号| 20 | 20 | No | 没有 29-Dec-2015 | 2015年12月29日|

Note : There is no foreign key association between both the tables. 注意 :两个表之间没有外键关联。

You have to JOIN both tables on the id and grade fields. 您必须在idgrade字段上都加入两个表。

SELECT b.ID, b.Grade, a.Student_Count, b.Visited, b.Visit_date
FROM table2 b 
INNER JOIN table1 a 
ON a.ID = b.ID AND a.Grade = b.Grade
ORDER BY a.ID

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

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