简体   繁体   English

MySQL联接查询与where条件和不同的记录

[英]Mysql join query with where condition and distinct records

I have two tables called tc_revenue and tc_rates . 我有两个称为tc_revenuetc_rates表。

  • tc_revenue contains :- code, revenue, startDate, endDate tc_revenue包含:-代码,收入,startDate,endDate
  • tc_rate contains :- code, tier, payout, startDate, endDate tc_rate包含:-代码,层,支出,startDate,endDate

Now I need to get records where code = 100 and records should be unique.. 现在,我需要获取代码= 100且记录应该唯一的记录。

I have used this query 我用过这个查询

SELECT * 
FROM task_code_rates 
LEFT JOIN task_code_revenue ON task_code_revenue.code = task_code_rates.code
WHERE task_code_rates.code = 105;

But I am getting repeated records help me to find the correct solution. 但是,我不断获得记录,可以帮助我找到正确的解决方案。

eg: 例如:

在此处输入图片说明

in this example every record is repeated 2 time 在此示例中,每条记录重复2次

Thanks 谢谢

Use a group by for whatever field you need unique. 将分组依据用于您需要唯一的任何字段。 For example, if you want one row per code, then: 例如,如果您希望每个代码一行,那么:

SELECT * FROM task_code_rates LEFT JOIN task_code_revenue ON task_code_revenue.code = task_code_rates.code
where task_code_rates.code = 105
group by task_code_revenue.code, task_code_revenue.tier

If code admits duplicates in both tables and you perform join only using code, then you will get the cartessian product between all matching rows from one table and all matching rows from the other. 如果代码在两个表中都允许重复,而您仅使用代码执行联接,那么您将获得一个表中所有匹配行与另一个表中所有匹配行之间的笛卡尔积。

If you have 5 records with code 100 in first table and 2 records with code 100 in second table, you'll get 5 times 2 results, all combinations between matching rows from the left and the right. 如果在第一张表中有5条代码为100的记录,在第二张表中有2条代码为100的记录,则将获得5乘以2的结果,即左右匹配行之间的所有组合。

Unless you have duplicates inside one (or both) tables, all 10 results will differ in colums coming either from one table, the other or both. 除非您在一个(或两个)表中有重复项,否则所有10个结果在一个表,另一个表或两个表的列中都会有所不同。

But if you were expecting to get two combined rows and three rows from first table with nulls for second table columns, this will not happen. 但是,如果您期望从第一张表中获得两行和三行的组合,而第二张表中的列为空,则不会发生这种情况。

This is how joins work, and anyway, how should the database decide which rows to combine if it didn't generate all combinations and let you decide in where clause? 这就是联接的工作方式,无论如何,如果数据库未生成所有组合并让您决定在where子句中,数据库应如何决定合并哪些行?

Maybe you need to add more criteria to the ON clause, such as also matching dates? 也许您需要向ON子句添加更多条件,例如匹配日期?

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

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