在SQL中从一个表更新一个表的最佳方法是什么?

时间:2016-12-21 16:00:46

标签: php mysql sql inner-join exists

我有2个表,第一个是产品页已访问

+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| idproduct  | varchar(128) | YES  |     | NULL    |                |
| logdate    | date         | YES  |     | NULL    |                |
| idmagasin  | int(20)      | YES  |     | NULL    |                |
| idenseigne | int(20)      | YES  |     | NULL    |                |
| commanded  | int(2)       | YES  |     | 0       |                |
+------------+--------------+------+-----+---------+----------------+

第二个是产品命令

+-------------+--------------+------+-----+-------------------+----------------+
| Field       | Type         | Null | Key | Default           | Extra          |
+-------------+--------------+------+-----+-------------------+----------------+
| id          | int(11)      | NO   | PRI | NULL              | auto_increment |
| idproduct   | varchar(255) | NO   |     | NULL              |                |
| idenseigne  | int(11)      | NO   |     | NULL              |                |
| idmagasin   | int(11)      | NO   |     | NULL              |                |
| ingredients | tinytext     | YES  |     | NULL              |                |
| date        | timestamp    | NO   |     | CURRENT_TIMESTAMP |                |
+-------------+--------------+------+-----+-------------------+----------------+

如何更新product_visited中的命令列,if product_visited.idproduct = product_commanded.idproduct and product_visited.logdate = product_commanded.date

我很难使用内部联接存在

我希望update product_visited.commanded = 1当product_commands中存在logdateidproduct的值时,这意味着所访问的产品也被命令

3 个答案:

答案 0 :(得分:2)

我相信这就是你要找的东西:

Update product_visited pv
    set commanded = 1
    Where exists (Select 1
                  from product_commanded pc
                  where pv.idproduct = pc.idproduct and pv.logdate = pc.date
                 );

答案 1 :(得分:1)

好的,我已经对加入字段做了猜测,但你是在这样的事情之后做的;

UPDATE pv
SET pv.Commanded = 1
FROM Product_Visited pv
JOIN Product_Commanded pc
    ON pv.logdate = pc.date
    AND pv.idproduct = pc.id

内连接意味着您只需更新Product_Visited中的记录,其中Product_Command中的匹配行基于您提供的连接谓词。

注意:这是SQL Server的答案。可能或可能不适用于MySQL

答案 2 :(得分:1)

class SimpleConnection(connection.SSHConnection): def serviceStarted(self): self.openChannel(CommandChannel(conn=self)) class CommandChannel(channel.SSHChannel): name = 'session' def channelOpen(self, data): global command command = "ls" d = self.conn.sendRequest(self, 'exec', common.NS(command), wantReply=True) d.addCallback(self.dataReceived) def dataReceived(self, data): print (data) def closeReceived(self): self.conn.openChannel(self) 表中同一产品的记录存在时,您想要更新commanded

在任何数据库中:

commanded