0

in old time for select data from two or more tables i use this way: for example

SELECT id,name FROM table WHERE ...
// and after get data, use second request
SELECT title FROM table_two WHERE id=$ID
// and here, id come from first query

after a while i found out this way:

SELECT t1.id,t1.name,t2.title FROM table as t1,table_two as t2 WHERE ... AND t1.id=t2.id

then in one query i get all data i want from both tables or even more (e.g. fetch data from 4 tables)

but i wondering is this a good way to get data or not? should i use JOIN in my query? can you give me an example of JOIN for this one:

SELECT t1.id,t1.name,t2.title FROM table as t1,table_two as t2 WHERE ... AND t1.id=t2.id

is this way make any problems for large DB?

Dharman
  • 30,962
  • 25
  • 85
  • 135

1 Answers1

0

Below query is using INNER JOIN for you

SELECT t1.id,t1.name,t2.title 
 FROM table as t1 
 INNER JOIN table_two as t2 ON t1.id=t2.id
 WHERE ... AND 

If you have large data,then there are multiple ways to improve query performance:

  1. only get required column,not *
  2. add index to the related column
  3. Using WHERE to filter unrelated data
  4. Using partition to devide data
flyingfox
  • 13,414
  • 3
  • 24
  • 39
  • thank you so much for INNER JOIN, is this better than my way or they are the same? – user19014207 Nov 26 '22 at 06:52
  • and thanks again, i never use * and always put column name in my query, and id is primary column – user19014207 Nov 26 '22 at 06:54
  • @user19014207 You can check [whats-the-difference-between-where-clause-and-on-clause-when-table-left-joi](https://stackoverflow.com/questions/8311096/whats-the-difference-between-where-clause-and-on-clause-when-table-left-joi) – flyingfox Nov 26 '22 at 07:03