开发者

mysql multi table foreign keys? - beginner

开发者 https://www.devze.com 2023-01-31 23:11 出处:网络
I have 2 tables, Table1: id, int1, int2, i开发者_运维问答nt3 john,1,2,4 tim,2,3,4 pete,1,3,4 Table2:

I have 2 tables,

Table1: 
id, int1, int2, i开发者_运维问答nt3
john,1,2,4
tim,2,3,4
pete,1,3,4

Table2:
integer,blob
1,wins
2,backtickle
3,text
4,whatever

The query I want to use is given the id I want to get the blob data from table2 associated with each of the integer columns in table1.

What is the specific query I can use here?

Sample result I am looking for would be something like:

search John returns "wins","backtickle","whatever"

search pete returns "wins","text","whatever"

I think it has something to do with foreign keys, but not sure...beginner level please! With 1 table it would be SELECT * FROM table1 WHERE id="........" but not sure with the setup i have now given above.


The structure of your database does not look optimal. You're limiting yourself to 3 items per person, and you're using columns instead of rows in order to list them. What you actually have in your data is a many-to-many relationship between Table1 and Table2. What I'd recommend is using three tables:

Persons: 
name, personid
john,1
tim,2
pete,3

PersonBlobs:
personid, blobid
1,1
1,2
1,4
2,2
2,3
2,4
3,1
3,3
3,4

Blobs:
blobid,blob
1,wins
2,backtickle
3,text
4,whatever

PersonBlobs would give you the many-to-many link between Persons and Blobs.

And then the query becomes:

select Blobs.blob
from Blobs inner join PersonBlobs on Blobs.blobid = PersonBlobs.blobid
           inner join Persons on PersonBlobs.personid = Persons.personid
where Persons.name = 'John'
0

精彩评论

暂无评论...
验证码 换一张
取 消