Mark all selected columns after SELECT Statement - php

I am selecting a random selection of a table and want to mark the selected columns. I have an 'exported' column which is binary and is set 0 by default. When selecting it I want it to become 1. I thought of combining a SELECT and INSERT statement like:
SELECT id, status, vorname, nachname, strasse, hnr, plz, ort, telefon1, telefon2
FROM adressen
WHERE (vorname LIKE ? OR nachname LIKE ?)
ORDER BY RAND() LIMIT ?
AND INSERT INTO adressen (exported) VALUES '1'
but this seems to be not the right approach. The select statement works perfectly fine just as I want it to be but I don't know how to set the exported column to 1 for every selected row. Since the data is selected randomly I can't just do an insert statement after it since it won't match the same selected ones.

Save the results in a temporary table and then use update:
CREATE TABLE temp_results AS
SELECT id, status, vorname, nachname, strasse, hnr, plz, ort, telefon1, telefon2
FROM adressen
WHERE (vorname LIKE ? OR nachname LIKE ?)
ORDER BY RAND()
LIMIT ?;
Then:
update adressen a join
temp_results r
on a.id = r.id
set exported = 1;
Note: This assumes that id is unique. If it is not, use the primary key on the table.
I also suspect that your query probably wants something like exported = 0.

Related

Why does multiple WHERE conditions in a PDO prepared SELECT statement cause the query to break

When this query is executed I get the response (through AJAX) I expect. It works.
$stmt = $pdo->prepare("SELECT item_location AS Location, users_description AS Description, price AS Price FROM sale_items WHERE item_type IN ($cs_vals)”);
But when I add another table column name to the WHERE clause like so:
$stmt = $pdo->prepare("SELECT item_location AS Location, users_description AS Description, price AS Price FROM sale_items WHERE (item_type, map_region) IN ($cs_vals)”);
....I get a 'JSON.parse: unexpected character....' message in the console and nothing displayed in my webpage. Why is this? What am I doing wrong here. Thanks in advance for any help.
BTW, $cs_vals is a list of comma separated values in the format ('a', 'b', 'c'...). This comma separated list has been generated by
$cs_vals = str_repeat('?,', count($arr) - 1) '?';
The $arr variable is an array of non NULL values extracted from a user generated form.
I am assuming you know about the FROM
You have to check one at a time:
WHERE ((item_type) IN ($cs_vals)
OR (map_region) IN ($cs_vals))
Unless you are trying to find the combo in an array.
You use EXISTS and instead of $cs_vals you create an inline table using UNION so you can validate if the tuple match your list.
SQL DEMO
SELECT item_location AS Location, users_description AS Description, price AS Price
FROM sale_items
WHERE EXISTS (SELECT 1
FROM (SELECT 'A' as item_type, 1 as map_region
UNION
SELECT 'B' as item_type, 2 as map_region
) as T
WHERE sale_items.item_type = T.item_type
AND sale_items.map_region = T.map_region
)
Also you can use IN but need compare with tuples like this:
SELECT item_location AS Location, users_description AS Description, price AS Price
FROM sale_items
WHERE (item_type, map_region) IN (('A',1),('B',2));

if not exist and getting proper values from databse

I am trying to insert list of items from dev.test1 table, but I am struggling with logic ...
Face following problems:
Before insert statements I would like to add "if not exists" - select content in dev.qa_postmetas
f.URL which I am getting in second query is not coming from correct row in dev.test1 - If want to select f.URL where f.title = b.title
Query:
INSERT INTO dev.qa_posts (type, categoryid, userid, created, title, content, tags)
(SELECT 'Q_QUEUED', '1', '3', NOW(), f.title, f.img, f.tagsv
FROM dev.test1 f)
LIMIT 1;
INSERT INTO dev.qa_postmetas (postid, title, content)
(select MAX(b.postid) , 'qa_q_extra',f.URL
from dev.qa_posts b
left JOIN dev.test1 as f on b.postid = f.id)
LIMIT 1 ;
Any assistance will be appreciated
To avoid emty records try IS NULL function in MySQL.
Second query you join to another one and limiting insertion to one.
You may have more results from joined query then you attemt to insert.
Debug your second join select to check what results you have.
Take out limitation to insert all records from joined queries.
Is that what you mean?

MySql - if there is no record, insert multiple rows

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

SQL insert into select from multiple fields

I have a table 'users' with a column of 'ID'. I want to select 2 different 'ID's' based on 2 different parameters and insert them both into another table known as 'jobs'.
INSERT INTO jobs (customer_id, client_id)
SELECT id, id from users
WHERE username = ?
AND username = ?
Basically I want to get the ID of two different people and insert them both into the new table.
I would then bind the parameters to ?, and they would look something like 'john' and 'steve'. I have tried the code above but I know it is the wrong syntax. Any ideas would be greatly appreciated. Thanks
You could use a self-join:
INSERT INTO jobs
(customer_id, client_id)
SELECT customer.id, client.id
FROM users customer
JOIN users client ON customer.username = ? AND client.username = ?
Or, you could use subqueries:
INSERT INTO jobs
(customer_id, client_id)
VALUES (
(SELECT id FROM users WHERE username = ?),
(SELECT id FROM users WHERE username = ?)
)
Well, you could use subquerys
INSERT INTO jobs (customer_id, client_id)
VALUES (
(SELECT field from table where id = 2),
(SELECT field from table2 where id = 12)
)
I'm not pretty sure about the sintax, since I haven't tested, but I'm guessing it could solve it.
I often use such things in WHERE or in the SELECT statement. Just remember to return a single field and a single row in the subquerys.

sort same field from different tables

I have somes tables (around 20) with the same structure and I'm trying to sort them with a php script and insert them in a new table with the cheapest price in cheapest1, then cheapest2 for more expensive... and the most expensive in column cheapest20:
table A:
id
name
price
table B:
id
name
price
table X:
id
name
price
tableResult:
id
name
cheapest1
price1
cheapest2
price2
...
cheapestX
priceX
My code so far is:
(SELECT id, price, name FROM tableA WHERE id = $id)
UNION
(SELECT id, price, name FROM tableB WHERE id = $id)
ORDER BY price ASC
I have been looking for different solutions but it takes too long to SELECT for 15000 rows so I guess there is another way to do it.
I haven't looked for the update query yet, I need to fix the select in the first time.
Any suggestion?
EDIT: clarified question, with more tables
EDIT2: solution
I finally got it right. This is the query to select the cheapest:
I select each id and I browse:
(SELECT price AS P1, name, id FROM tableA WHERE id = ?) UNION (SELECT price AS P1, name, id FROM tableB WHERE id = ?) UNION (SELECT price AS P1, name, id FROM tableC WHERE id = ?) ORDER BY P1 ASC
Then I Insert in the new table as glglgl suggested:
('INSERT INTO table (id, name, Position, price) VALUES (?, ?, ?, ?) ');
If you have control over the final structure of the tables: Don't do that. Instead, use only one table and add a field for indicating which purpose it serves.
The target table is not structured well either. Instead, you should use
tableResult:
id
name
cheapestorder
cheapest
price
which makes all easier.
Thus, instead of having one row containing
id=10, name=foo, cheapest1=a, cheapestprice1=10, cheapest2=b, cheapestprice2=13,
you have several rows
id=10, name=foo, cheapestorder=1, cheapest=a, cheapestprice=10
id=10, name=foo, cheapestorder=2, cheapest=b, cheapestprice=13
(This process is called "normalization" in database theory.)
Putting all input tables into one simplifies dcp's query:
SELECT name,
max(mxprice) mxprice,
min(mnprice) mnprice
FROM
(
SELECT name,
max(price) mxprice,
min(price) mnprice
FROM tableABC
GROUP BY NAME, tbltag
) a
GROUP BY NAME
or maybe even just
SELECT name,
max(price) mxprice,
min(price) mnprice
FROM tableABC
GROUP BY NAME
.
I did this on Oracle, but syntax should be very similar for MySQL (the select should work without any changes at all).
CREATE TABLE tableA (NAME VARCHAR2(100), price FLOAT);
CREATE TABLE tableB (NAME VARCHAR2(100), price FLOAT);
INSERT INTO tableA VALUES ('a',14.23);
INSERT INTO tableA VALUES ('b',15.23);
INSERT INTO tableA VALUES ('b',16.23);
INSERT INTO tableB VALUES ('a',12.23);
INSERT INTO tableB VALUES ('a',13.23);
INSERT INTO tableB VALUES ('b',9.23);
SELECT name
, max(mxprice) mxprice
, min(mnprice) mnprice
FROM
(
SELECT name
, max(price) mxprice
, min(price) mnprice
FROM tableA
GROUP BY NAME
UNION ALL
SELECT name
, max(price) mxprice
, min(price) mnprice
FROM tableB
GROUP BY NAME
) a
GROUP BY NAME
Result:
NAME MXPRICE MNPRICE
1 a 14.23 12.23
2 b 16.23 9.23

Categories