简体   繁体   中英

In MySQL, how do I do an insert based on a join condition?

Thanks for looking!

Background

I have virtually no experience with the LAMP stack, but I have recently started an online store that uses OpenCart which is based on the LAMP stack.

The store allows for me to assign reward points to customers and I am giving each new customer 10 points just for creating an account.

Unfortunately, the OpenCart admin GUI only allows me to do this manually, one user at a time.

I do, however, have access to an interface that will allow me to run MySql commands and I would like to solve the problem using this approach.

Within the database created by OpenCart, I have a oc_customer table which contains all of my customers, and then I have a oc_customer_reward table which keys off of the customer id and assigns a new record each time a customer is awarded points. Here is what that looks like:

oc_customer_reward

Question

How do I write a MySql query that will see if a customer from oc_customer does NOT exist in the oc_customer_reward table and IF THEY DO NOT EXIST, then create a record in the oc_customer_reward table (worth 10 points) for that customer?

I am not asking for working code (unless you really want to provide it) and I am willing to do the work myself, but frankly I don't know where to start. What would be the approach?

UPDATE

Per Olaf's suggestion, I am able to get all customers NOT in the oc_customer_reward table with his suggested query:

SELECT customer_id
FROM oc_customer
WHERE customer_id NOT 
IN (
SELECT customer_id
FROM oc_customer_reward
)

Now, I just need to iterate the results of that query (sorry I am not a database guy!) and insert a row in oc_customer_reward for each of them. Kind of like a foreach loop in C#. Any thoughts?

First find customers not in the reward table:

select customer_id from oc_customer
    where customer_id not in (select customer_id from oc_customer_reward);

then take that and insert an entry into the reward table:

insert into oc_customer_reward (customer_id, points)
    select customer_id, 10 from oc_customer
        where customer_id not in (select customer_id from oc_customer_reward);

This is not tested, but I hope it helps for a start.

Not tested and unsure about the table structure of oc_customer but following query should help you

INSERT INTO oc_customer_reward ( customer_id, description, points, date_added ) 
 SELECT customer_id, 'reward for registration', 10, CURRENT_TIMESTAMP FROM oc_customer WHERE NOT EXISTS ( SELECT * FROM oc_customer_reward r WHERE r.customer_id = oc_customer.customer_id );

More details about the EXISTS statement you can find here

http://dev.mysql.com/doc/refman/5.5/en//exists-and-not-exists-subqueries.html

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