duanhu7615 2016-11-20 20:52
浏览 14
已采纳

如何根据2个外键使用不同的主键

So I have a table in MySQL that has the rows Date, Username, and Hours. 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

Since a User can only work X hours on a certain day, but can obviously work many days. 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

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. But that seems like an Ugly work around, surely there has to be a way to achieve this.

  • 写回答

1条回答 默认 最新

  • dongliao3450 2016-11-20 22:10
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:使用ATL02数据解算光子脚点的坐标(操作系统-windows)
  • ¥115 关于#python#的问题:未加密前两个软件都可以打开,加密后只有A软件可打开,B软件可以打开但读取不了数据
  • ¥15 在matlab中Application Compiler后的软件无法打开
  • ¥15 想问一下STM32创建工程模板时遇到得问题
  • ¥15 Fiddler抓包443
  • ¥20 Qt Quick Android 项目报错及显示问题
  • ¥15 而且都没有 OpenCVConfig.cmake文件我是不是需要安装opencv,如何解决?
  • ¥15 oracleBIEE analytics
  • ¥15 H.264选择性加密例程
  • ¥50 windows的SFTP服务器如何能批量同步用户信息?