Including items from various tables in a query MySQL.


I need to generate a MySQL query based on a field from a table. My database contains 2 tables. On each record found by the query  I need to include data from the other table. This other data should be linked based on a specific field on the record found by the main query.
Hope I have explained myself.

Who is Participating?
Cornelia YoderConnect With a Mentor ArtistCommented:
SELECT t1.FieldA, t2.FieldB FROM Table1 as t1, Table2 as t2 WHERE t1.KeyA=t2.KeyB
Your question is kinda vague, but you can do a new SELECT in the WHERE-clause.

SELECT name FROM table1 WHERE id=(SELECT id FROM table2 WHERE field=3)
theGhost_k8Connect With a Mentor Database ConsultantCommented:
watch out for join.
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

Ara-Connect With a Mentor Commented:
Ah. I can see I read the question wrong.

yodercm's example with JOIN:

SELECT t1.FieldA, t2.FieldB FROM Table1 as t1 JOIN Table2 as t2 ON t1.KeyA=t2.KeyB
Perhaps you could provide a bit more info and some sample data but I think you are trying to do this below ?

select * from tableA, tableB where tableA.ID = tableB.ID

Cornelia YoderArtistCommented:
Don't use JOIN unless you absolutely have to, it's much messier and complicated to understand and debug.
Tomas Helgi JohannssonCommented:

To speed up the query make sure that you have indexes on both tables
that matches the columns you use in the where clauses of the query . :)

    Tomas Helgi
lxfdirsAuthor Commented:

Thank you all for the suggestions.
I will be checking on them and come back to you with the accepted solution.

Guy Hengel [angelIII / a3]Billing EngineerCommented:
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.