简体   繁体   中英

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. So the way I'm doing it is like this. I have a table called products which contains products that people can 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. What would be a good way to do this using sql? Is it possible? Using foreign keys or something like that?

I'm using innodb table type.

You can do a conditional insert . For product 6 and user 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.

If you just want to phrase the insert so it follows the rules, then you can use insert . . . select insert . . . select insert . . . select as follows:

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.

And, you shouldn't put the product name int he likes table. You should look it up in the products table.

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.

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. 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. 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 ); } 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. 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.

--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.

Currently you require the prodId to populate the likes table, hence you need to lookup the data regardless of the contraint regarding blocked. 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).

Yuo need to query database to check record,

for example you product id is 2 so your query would be something like

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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