简体   繁体   English

如何基于2个外键来拥有不同的主键

[英]How to have a distinct Primary Key based off of 2 Foreign Keys

So I have a table in MySQL that has the rows Date , Username , and Hours . 所以我在MySQL中有一个表,其中有行DateUsernameHours What I want to be able to do is to generate a Primary key based off two foreign key values being Date and Username referenced from another table 我想要做的是基于另一个表中引用的DateUsername两个外键值生成主键

Since a User can only work X hours on a certain day, but can obviously work many days. 由于用户在某一天只能工作X个小时,但是显然可以工作许多天。 Then of course multiple Users can work on the same day. 然后,当然有多个用户可以在同一天工作。 But what would distinguish them is their Username. 但是区别他们的是他们的用户名。 And what would distinguish each particular user apart from himself is the days that they worked. 每个用户与众不同的是他们工作的日子。

What I want to be able to do with this generated PK field is have a SQL query like 我想要使​​用此生成的PK字段执行的操作是使用类似SQL查询

INSERT INTO Shift (`Date`, `Username`, `Hours`)
VALUES('$Date', '$username', 5) 
ON DUPLICATE Key UPDATE `Date` = '$today', `Username`= '$username', Hours= $TotalHr

I've considered just making a SQL Query in PHP to test if it the Username and Date are in the table, and either doing an insert or update from there. 我考虑过只使用PHP进行SQL查询以测试用户名和日期是否在表中,然后从那里进行插入或更新。 But that seems like an Ugly work around, surely there has to be a way to achieve this. 但这似乎是一个丑陋的工作,当然必须有一种方法来实现这一目标。

A combined primary key is also called a composite key. 组合的主键也称为组合键。 An example table with these keys would be: 具有这些键的示例表为:

CREATE TABLE Shift(
   Date DATETIME,
   Username VARCHAR(75),
   Hours INT(11),
   PRIMARY KEY (Date, Username)
) 

You could ofcourse also alter your table with a query. 您当然也可以通过查询更改表。

ALTER TABLE Shift
ADD PRIMARY KEY (Date, Username)

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

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