简体   繁体   English

mysql多表外键? -初学者

[英]mysql multi table foreign keys? - beginner

I have 2 tables, 我有2张桌子

Table1: 
id, int1, int2, int3
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. 我要使用的查询给出的ID是我想从与table1中每个整数列相关联的table2中获取blob数据。

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" 搜索John返回“ wins”,“ backtickle”,“ whatever”

search pete returns "wins","text","whatever" 搜索pete返回“ 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. 对于1个表,它将是SELECT * FROM table1 WHERE id =“ ........”,但不确定我上面给出的设置。

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. 您将自己限制为每人3件物品,并且使用列而不是行来列出它们。 What you actually have in your data is a many-to-many relationship between Table1 and Table2. 您数据中实际拥有的是Table1和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. PersonBlob将为您提供Persons和Blob之间的多对多链接。

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'

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

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