MySql - if there is no record, insert multiple rows - php

Before asking this question, I already search a lot of entries on Google and StockOverflow. Nothing can fulfil my question.
There are two tables - group_sale_bonuses and members. I want to check is already there records with product_id "1" in the group_sale_bonuses.
If not, I want to insert all records from members table into group_sale_bonuses with product_id "1".
My overall requirement is as follow:
IF ((Select count(id) from group_sale_bonuses where product_id = 1) = 0) THEN
INSERT INTO group_sale_bonuses (member_id, product_id, quantity_counter, credit)
SELECT id, 1, 0, 0 FROM members
END IF
But this sql causes the errors.
I know there are solutions about Insert Ignore, Where Not Exists.
But these conditions checking are based on per each record. I have thousands of records in members table. I want to make condition checking just one time like in my above sql example.
By the way, I will use this Sql in Php web application.

You could just set the code in a WHERE clause instead of the IF.
INSERT INTO group_sale_bonuses(
member_id,
product_id,
quantity_counter,
credit)
SELECT
id, 1, 0, 0 FROM members
WHERE(
SELECT
count(id) FROM group_sale_bonuses
WHERE product_id = 1
) = 0;

This should do it for all product_id's
SELECT m.product_id, m.member_id FROM members AS m
LEFT JOIN group_sale_bonuses AS gsb ON gsb.product_id = m.product_id
WHERE gsb.product_id IS NULL ;
You can filter it to a specific product_id by adding to the where clause
SELECT m.product_id, m.member_id FROM members AS m
LEFT JOIN group_sale_bonuses AS gsb ON gsb.product_id = m.product_id
WHERE gsb.product_id IS NULL AND m.product_id = 1;
Take a look at this SQLfiddle: http://sqlfiddle.com/#!2/8482c/2

Related

What join to use

I have two tables, one for registered users and one to store votes.
We are logging in with registrants.id and registrants.zipcode. Once they vote their votes are inserted into the votes table, along with their Registration ID.
Im trying to right a select statement that returns a record that will select all the records for Matched ID and Zipcode, but the ID is not in the Votes.voter column. i have tried all kinds of variations of all the joins i can think of. is it something simple i am missing.
SELECT * FROM registrants
LEFT JOIN votes on registrants.id = votes.voter
WHERE registrants.id = 1 AND registrants.zipcode = 46706 and votes.voter <> 1
Perhaps a not exists query:
select * from registrants
where registrants.zipcode = '46706'
and not exists (select 1 from votes where registrants.id = votes.voter)

Sorting data from MySQL by SUM with Grouping By - not working properly

I have a problem with mysql - i'm kind new to it, byt looking to improve my skills :)
Have a code like this:
if($where > 0) $query = mysql_query("SELECT img.*, user.user as owner_name, cat.name as cat_name FROM tentego_img AS img LEFT JOIN tablicacms_users AS user ON user.id = img.owner LEFT JOIN tentego_img_cat AS cat ON cat.id = img.cat WHERE img.`is_waiting` LIKE ".$where.$cat." INNER JOIN tentego_img_vote ON tentego_img.id = tentego_img_vote.object_id GROUP BY tentego_img_vote.object_id ORDER BY SUM ( (CASE WHEN tentego_img_vote.vote = '0' THEN '-1' ELSE '1' END) ) DESC LIMIT ".$page.",".$objPerPage);
I need to make sorting by number of votes, sorted descending.
Still it makes results sorted by it own way.
In table I have rows:
ID - vote id for table purpose
object_id- id of object joined with another table to show results.
User ID - user id
Vote - where values are 0 for dislike and 1 for like (so -1 for 0, and +1 for 1)
So, as I understand i need to sum up all records for each of unique object_id, then sort by sum of vote values of each.
This code worked before my script provider decide to upgrade it, so right now i dont know how to fix it :(

Need help writing an SQL query for a select statement

I need help with an SQL query.
I want to show lines from my test_related_orders table where the current user id equals the user_id in my test_related_orders table and where order_unlock_time (from my table) is <= acutal timestamp. Until here all works fine. But now it gets complicated.
I also need to check/restrict in my wp_posts table if there is an post_author equals to my test_related_orders user_id who has an existing order_number same as from my test_related_orders order_number.
If this statement is true the associated lines from my test_related_orders will be shown. If this statement is false there should be no associated lines.
(So when I delete an order in the woocommerce frontend the statement should'nt return a string for this entry.)
Here is my existing code:
$user_id = get_current_user_id();
//Timestamp for current system time
date_default_timezone_set("Europe/Berlin");
$timestamp = date("Y-m-d H:i:s");
//Database Query
$abfrage = "SELECT * FROM test_related_orders WHERE user_id = '$user_id' AND order_unlock_time <= '$timestamp'";
I think I can use an INNER JOIN and I've tried it here:
INNER JOIN wp_posts ON '$user_id' = post_author WHERE....
but it's to complicated for me as a beginner.
Here are my database structures:
The test_related_orders structure:
The order_number looks like: DE-1016-835 and the user_id as a normal number/id like 1 in this example.
The wp_posts database structure:
The last picture is an example entry from the wp_posts. The problem is that I have to grab the order number from post_title and for this I have to remove the first word "Lieferschein" from this title to get the order_number and there's no extra field for the number...
Thank you for your help! I hope I explained it completely.
First problem to solve is getting the order number from the post_title so that you can compare the values in your inner join. A primitive way of doing this, assuming the order number is always in form AA-DDDD-DDD would be
SELECT right(post_title, 11) as posts_order_number
As you've already discovered, an inner join is what you need, as it'll only return results where the tables match. Note you usually join tables based on their columns, rather than directly comparing to your '$user_id' string (and you've already filtered for this in your where clause).
You can join on more than one field at a time, to match on order number as well as user_id.
Your query now becomes:
SELECT *
FROM test_related_orders tro
INNER JOIN wp_posts p
ON tro.user_id = p.post_author
AND tro.order_number = right(p.post_title, 11)
WHERE tro.user_id = '$user_id' AND order_unlock_time <= '$timestamp'

Distinct Values from MySQLi Query

I am trying to only show unique userIds (userIds are (0,1,2,3,4,5,6,7,8,9 etc...) for the query I am running. I tried using DISTINCT in my query, but it only shows me unique values of the rows that have 2 or more of the same userId.
Is there a way I can use php to only show the unique values. My weak points are arrays and it makes it more complicated because its using data from a MySQLi query.
Example right now I have with the query now (lets say its GROUP BY rentPaid DESC and the rent total is 800.00 for all users):
userID rentPaid rentMonth
2--------800.00------April
1--------500.00------April
3--------400.00------April
3--------400.00------April
1--------200.00------April
1--------100.00------April
Example desired output:
userID rentPaid rentMonth
2--------800.00------April
1--------500.00------April
3--------400.00------April
Can I do this with MYSQL because I tried DISTINCT and it wouldn't work, how about PHP?
Query:
SELECT
properties.*,
leases.*,
users.userId, users.primaryPhone,
CONCAT(users.userFirstName,' ',users.userLastName) AS user,
admins.adminName, payments.*
FROM
properties
LEFT JOIN leases ON properties.propertyId = leases.propertyId
LEFT JOIN assigned ON properties.propertyId = assigned.propertyId
LEFT JOIN admins ON assigned.adminId = admins.adminId
LEFT JOIN users ON properties.propertyId = users.propertyId
LEFT JOIN payments ON properties.propertyId = payments.propertyId
WHERE
payments.rentMonth = '$currentMonth' AND
payments.rentYear = '$currentYear'
Edit: Please excuse my formatting, this is my first post.
Edit: Added query....its long, but works lol. I only want unique userIds (no double or triple userIds etc...)
I suspect this is what you want:
SELECT userID, MAX(rentPaid) AS maxRentPaid, rentMonth
FROM yourTable
WHERE rentMonth = "April"
GROUP BY userID
ORDER BY maxRentPaid

PHP/MySQL Using multiple WHEREs in one SELECT query

I have 2 tables.
Table A: trades: which contains the columns: tradeID, tradeName, tradeShow, and tradeGuy.
Table B: offers: which contains the columns: tradeID, offerName, offerGuy.
I'm trying to select all columns from table A (trades) WHERE the value of "tradeShow" = 'Yes', And the value of "tradeGuy" != the user's Username. That much is easy, but I also don't want to select any records which have an offer created by the user. In other words, in table B (offers), offerGuy != Username WHERE trade ID from Table B = tradeID from Table A.
But, how do I merge these 2 conditions? I've tried this:
$sql = "SELECT *
FROM trades t1
JOIN offers t2
ON (t1.tradeID = t2.tradeID)
WHERE t1.tradeShow='Yes' AND t1.tradeGuy!='$username' AND t2.offeringGuy!='$username'";
But the problem with that is it only selects the records from trades which have an offer, because of the forth line: ON (t1.tradeID = t2.tradeID), as in it only selects trades which have a record in (offers) that mentions their tradeID.
I've also tried an awkward attempt to link the 2 tables with a meaningless link by adding a "linker" column to each table with the default value of "XXX", and did this:
$sql = "SELECT *
FROM trades t1
JOIN offers t2
ON (t1.linkerA = t2.linkerB)
WHERE t1.tradeShow='Yes' AND t1.tradeGuy!='$username' AND (t2.offeringGuy!='$username' WHERE t1.tradeID=t2.tradeID)";
But the problem with that is using 2 Where clauses...
So, how do I merge the 2 conditions?
What you're looking for is called an OUTER JOIN (in this case a LEFT OUTER JOIN) which will give you null results for missing matches, something like;
SELECT *
FROM trades t1
LEFT OUTER JOIN offers t2
ON t1.tradeID = t2.tradeID AND t2.offeringGuy = '$username'
WHERE t1.tradeShow='Yes' AND t1.tradeGuy!='$username' AND t2.offeringGuy IS NULL
We add a condition to the LEFT JOIN that we're only interested in matches against t2.offeringGuy = '$username', which will return NULL values in t2's fields if there is no match.
Then we just check that t2.offeringGuy IS NULL to find the non matches.
I would do this with not exists rather than an explicit join:
SELECT *
FROM trades t
WHERE t.tradeShow = 'Yes' AND t.tradeGuy <> '$username' and
not exists (select 1
from offers o
where t.tradeID = o.tradeID and o.tradeGuy = '$username'
);

Categories