简体   繁体   English

在将一个表添加到另一个表之前检查表中是否存在一个ID

[英]Check if an id exists in a table before adding it to another table

I'm doing a small thing like the like feature you see on facebook. 我正在做like您在Facebook上看到的功能的小事情。 So the way I'm doing it is like this. 所以我做的方式就是这样。 I have a table called products which contains products that people can like . 我有一个称为products的表,其中包含人们like Like this (stripped down): 像这样(分解):

id | prodName               | status (0=clear, 1=blocked)
----------------------------------------------------------
1  | Philips Food Processor | 0
2  | Le Sharp Knife         | 0
3  | Ye Cool Fridge         | 0

Then comes the `likes` table like this:
id | prodName               | prodId | userId
--------------------------------------------
1  | Philips Food Processor | 1      | 1
2  | Le Sharp Knife         | 2      | 1
3  | Ye Cool Fridge         | 3      | 1
4  | Ye Cool Fridge         | 3      | 2

I need to check, before adding to the likes table, if a product with that id actually actually exists in the products table and its status = 0. I currently do this with a lot of php code. 在添加到likes表之前,我需要检查是否具有相同ID的产品实际上存在于products表中,并且其状态=0。我目前使用大量的php代码来进行此操作。 What would be a good way to do this using sql? 什么是使用sql做到这一点的好方法? Is it possible? 可能吗? Using foreign keys or something like that? 使用外键或类似的东西?

I'm using innodb table type. 我正在使用innodb表类型。

You can do a conditional insert . 您可以执行条件insert For product 6 and user 7: 对于产品6和用户7:

insert  into Likes
        (prodName, prodId, userId)
select  prodName
,       id
,       7
from    Products
where   id = 6
        and status = 0

If this inserts no rows, you know that the product did not exist with status 0. 如果不插入任何行,则说明该产品不存在,状态为0。

If you just want to phrase the insert so it follows the rules, then you can use insert . . . select 如果您只想表达insert以使其遵循规则,则可以使用insert . . . select insert . . . select insert . . . select as follows: insert . . . select如下:

insert into likes(prodId, userId)
    select <prodid>, <userid>
    from products p
    where p.prodid = <prodid> and status = 0

I don't think MySQL supports "partial" foreign key constraints, where you can also include the requirement on the flag. 我不认为MySQL支持“部分”外键约束,您也可以在标记中包含要求。

And, you shouldn't put the product name int he likes table. 而且,您不应将产品名称放入他likes表中。 You should look it up in the products table. 您应该在products表中查找它。

The key element of trying to add something to the likes table that does not exist in the product table is the feedback to the user that lets them know they're doing it wrong. 尝试向“喜欢”表中添加产品表中不存在的某些内容的关键要素是对用户的反馈,使他们知道自己做错了。 Any answer you determine on should not ignore the user feedback side of things - which is basically going to require your PHP code. 您确定的任何答案都不应忽略用户反馈的一面-这基本上将需要您的PHP代码。

However, yes - there is a way to do it via foreign keys. 但是,是的-有一种方法可以通过外键来实现。 You can index the prodid in the second table, and reference it as a foreign key to the first table.id. 您可以在第二个表中建立索引,并将其作为第一个table.id的外键引用。 This means that if you try an insert and you get an error, there's a chance that the problem is that you're trying to add something without a match in the first table. 这意味着,如果您尝试插入但出现错误,则可能是您试图在第一个表中添加不匹配的内容。

However, trying to determine precisely what the error is so you can determine the proper logic to respond to that error causes its own mass of php code, and is less easily transparent for future developers to maintain. 但是,尝试精确地确定错误是什么,以便您可以确定响应该错误的适当逻辑,从而导致其自身的大量php代码,并且对于将来的开发人员而言,维护起来不那么透明。 I'd suggest a simple method in your Product object: isValid( id ) that returns true/false - so your 'check for this' code simply goes if( Product.isValid( prodId ) ){ Like.insert( userId, prodId ); } 我建议在您的Product对象中使用一个简单的方法: isValid( id ) ,该方法返回true / if( Product.isValid( prodId ) ){ Like.insert( userId, prodId ); }因此您的“检查此”代码就简单地通过if( Product.isValid( prodId ) ){ Like.insert( userId, prodId ); } if( Product.isValid( prodId ) ){ Like.insert( userId, prodId ); }

But at the same time, I'd REALLY recommend a foreign key constraint along with the php code you're probably already using, just as insurance against your database becoming cluttered with unlinked rows. 但是同时,我真的建议您使用外键约束以及可能已经在使用的php代码,以防止数据库因未链接的行而变得混乱。 It's usually best to have multiple barriers against bad data. 通常最好对不良数据设置多个障碍。

Additionally ... is there a reason why you're storing the product names both in the product table AND in the likes table? 另外...您为什么要在产品表和点赞表中同时存储产品名称? I don't see why you'd need it in the likes table. 我在Likes表中看不到为什么需要它。

--Check to see if cleared product exist in products table
Select count(*) from products p where p.status = 0 and p.id = %IDVALUE

--Check if your user previous liked product
Select count(*) from products p, likes l where p.id = l.prodId and l.userId = %USERID

In your code you can execute the statements (replace %IDVALUE and %USERID with actual values) and check the return column to get the count and preform your custom logic. 在您的代码中,您可以执行语句(将%IDVALUE和%USERID替换为实际值)并检查return列以获取计数并执行自定义逻辑。

Currently you require the prodId to populate the likes table, hence you need to lookup the data regardless of the contraint regarding blocked. 当前,您需要prodId来填充likes表,因此,无论与阻止有关的约束如何,都需要查找数据。 Hence: 因此:

INSERT INTO likes (prodname, prodId, userId)
SELECT prodname, id, 123456
FROM products
WHERE prodname='Le Sharp Knife'
AND status=0;

(just substitute 123456 and 'Le Sharp Knife' for the parameters you need). (只需将123456和“ Le Sharp Knife”替换为您需要的参数)。

Yuo need to query database to check record, 您需要查询数据库以检查记录,

for example you product id is 2 so your query would be something like 例如您的产品ID为2因此您的查询将类似于

$query = select * from 'your-like-table' where 'prodId ' = 'ID';

then 然后

if ( !mysql_query('your-db',$query)):

if you come under this condition then it's the time when you enter your like to database 如果您遇到这种情况,那就是您输入喜欢的数据库的时候

endif;

hope it helps 希望能帮助到你

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

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