如何在 mysql 中添加外键(带有 python 的连接器)

how to add a foreign key in mysql (connector with python)

我有 python 脚本的这一部分,可以将表创建到 mysql db

#Product
TABLES['product'] = (
"CREATE TABLE product"
 "(prod_id smallint,"
  "name varchar(255),"
  "price int,"
  "constraint pk_prod_id primary key (prod_id)"
 ");")

#Sales
TABLES['sales'] = (
"CREATE TABLE sales"
 "(sales_id smallint,"
  "name varchar(255),"
  "quantity int,"
  "buy_id smallint,"
  "date DATE,"  
  "constraint pk_sales_id primary key (sales_id,name)"
 ");")
#Purchase
TABLES['purchase'] = (
"CREATE TABLE purchase"
 "(purchase_id smallint,"
  "name varchar(255),"
  "quantity int,"
  "sup_id smallint,"
  "date DATE,"  
  "constraint pk_purchase_id primary key (purchase_id,name)"
  ");")

# Adding foreign key
query =  'ALTER TABLE sales ADD foreign key(buy_id) references buyers(buy_id)'
cursor.execute(query)
query = 'ALTER TABLE purchase ADD foreign key(sup_id) references suppliers(sup_id)'
cursor.execute(query)

到这里为止一切正常,但这是主要问题。

query = 'ALTER TABLE sales ADD foreign key(name) references product(name)'
cursor.execute(query)
query = 'ALTER TABLE purchase ADD foreign key(name) references product (name)'
cursor.execute(query)

错误码为1215,无法添加外键

如果我这样做就有效

query = ('ALTER TABLE sales ADD foreign key(prod_id) references product(prod_id)')
cursor.execute(query)
query = ('ALTER TABLE purchase ADD foreign key(prod_id) references product(prod_id)')
cursor.execute(query)

但我更喜欢使用 name 而不是 prod_id 因为它很乱。

我该如何解决这个问题?我尝试使用 int 类型,但我不喜欢这种解决方案,而且我必须重写很多查询。

使用 KEY(名称)制作 table 产品

#Product
TABLES['product'] = (
"CREATE TABLE product"
 "(prod_id smallint,"
  "name varchar(255),"
  "price int,"
  "constraint pk_prod_id primary key (prod_id),"
  "KEY (name)"
 ");")

并且您可以在没有问题的情况下向产品名称添加外键

谢谢,成功了。 但是以前的查询现在不再起作用了 例如,我可以做到这一点;

cursor = cnx.cursor()
date = str(input('insert a date in yyyy-mm-dd :'))
query = "SELECT SUM(DISTINCT p.price*s.quantity),COUNT(p.price*s.quantity) FROM product p JOIN sales s ON  p.name = s.name WHERE s.date > "
cursor.execute(query+"'"+date+"'")

for i,j in cursor:
    print("Number of sales {}\nMoney earned {}".format(j,i))

输出是这个

insert a date in yyyy-mm-dd :2019-06-03
Number of sales 5
Money earned 12750

现在这不再有效了。