Home  >  Article  >  Backend Development  >  How to obtain the value of the corresponding field in the related table when mysql main table is output?

How to obtain the value of the corresponding field in the related table when mysql main table is output?

WBOY
WBOYOriginal
2016-08-18 09:16:261461browse

As shown in the two tables in the figure, the salesperson field in Table 1 is associated with the number field in Table 2. How to obtain the value of the corresponding field in the related table when mysql main table is output?

If you want to output Table 1, it is time to automatically replace the salesperson number with the corresponding name. How to do this?

The current method that comes to mind is: first read the contents of Table 1, and then output it in a loop. In each loop, use the salesperson number to find the corresponding name in Table 2 and then output it.
Although it can be implemented, it doesn't feel like a formal method. The database must be read in each loop.
Is there a more scientific method?

Reply content:

As shown in the two tables in the figure, the salesperson field in Table 1 is associated with the number field in Table 2. How to obtain the value of the corresponding field in the related table when mysql main table is output?

If you want to output Table 1, it is time to automatically replace the salesperson number with the corresponding name. How to do this?

The method currently thought of is: first read the contents of Table 1, and then output it in a loop. In each loop, use the salesperson number to find the corresponding name in Table 2 and then output it.
Although it can be implemented, it doesn't feel like a formal method, and the database must be read in each loop.
Is there a more scientific method?

You should have just learned database...

Make a table join, left join table 1 to table 2, then select product, name, unit price
`select product, name, unit price
from table 1 left join table 2 on salesperson = number`

Suppose you have two tables, the first table is called table1 and the second table is called table2

select t1.商品, t2.名字, t1.单价 from table1 as t1 left join table2 as t2 on t1.销售员=t2.编号
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn