UPDATE/CREATE with LEFT JOIN multiple at a time - mysql

I'm working now on some dictionary and i'm downloading source from multiple dictionaries into mysql database.
I have two tables:
Words
ID and Word
ie. VALUES:
123, "Hakunamatata"
332, "Boom"
Source
ID, WordID and Numerical ie. VALUES:
1, 123, 7676552
2, 332, 651365
Now, i would like to update data in Source this way:
find ID in Words WHERE Word = "example"
put datum (WordID, "Number") into Source
BUT
If there is no such Word in Words - create it.
I need to do about 100000 of queries of this type, but it does not need to be very fast ;)
I've tried to do something like this:
REPLACE INTOsjp-dict.Words
LEFT JOINsjp-dict.Source-Wiktionary
ONWords.ID =Source-Wiktionary.WordID
SET
Word= IF(WordIS NULL, "Apulia",Word),
WordID= IF(Source-Wiktionary.WordID IS NULL ANDWord= "Apulia",Words.ID,WordID),
WikiWordID= IF(Word= "Apulia", 123, WikiWordID)
But it does not work...

Done with two sql commands:
$sql = 'INSERT IGNORE INTO Words (Word) VALUES '. $sql_words;
$sql2 = 'INSERT IGNORE INTO "Source-Wiktionary" (WordID, WikiWordID) VALUES '. $sql_values;
Where WordID is definied by
SELECT ID FROM Words WHERE Word = "'. strtolower($cma[2]). '" LIMIT 1

Related

Mysql query with column name in spaces

I have a table with columns machine id like (311a__) and (311bb__) and some of them like (08576). How can I retrieve them in SQL - how to insert into row where machine ID is like ( 311a__)? My question how to insert and select a column which has spaces in it.. How to retrieve data where machine_name ="%s__" is it correct
sql_local = """SELECT id FROM customer_1.pay_machines WHERE machine_name="%s" """ % machine
retVal = cursor.execute(sql_local)
if (retVal == 0):
sql_local = """INSERT INTO customer_1.pay_machines (machine_name, carpark_id) VALUES ("%s", 0)""" % machine
Surround odd (or reserved word) column names with backticks:
SELECT *
FROM pd
WHERE `machine id` = '(%s__)';
edit: removed invalid insert query as the first query is sufficient as an example

Insert values from two separate arrays into mysql table using Ruby

Suppose I have two different arrays.
Emails = ["email#email.com", "email1#email.com", "email2#email.com"]
Names = ["Name Surname", "Name1, Surname1", "Name2, Surname2"]
And I have a mysql-table called Contacts, which I want to insert each of the values into rows called Emails and Names. Each name and email should be inserted at their according indexes. So Emails[0] should be inserted along with Names[0], Emails[1] with Names[1] etc.
If there was only one array. I could do something like
sql = "INSERT INTO Contacts (email)
VALUES
('#{email}')
Emails.each do |email|
email = email.sql
end
but now I have two arrays and I need to put them so that each email is associated according to the correct name. How do I do this?
Use zip:
con.prepare "INSERT INTO Contacts(email, name) VALUES(?, ?)"
Emails.zip(Names).each do |email,name|
#insert into db
con.execute(email,name) #assuming **con** is your connection object
end
You could do something like this if you really want to iterate:
Email.zip(Names).each do |email, name|
sql = "INSERT INTO Contacts (email, name) VALUES ('#{email}', '#{name)')"
end
alternatively, you can probably bulk insert using
sql = "INSERT INTO Contacts (email, name) VALUES (" +
Emails.zip(Names).map { |e, n| "('#{e}', '#{n}')" }.join(",") + ")"
Looks kind of ugly, but you get the idea

mysql - insert many to many relationship

I am trying to insert records in 2 different mysql tables. Here's the situation:
Table 1: is_main that contains records of resorts with a primary key called id.
Table 2: is_features that contains a list of features that a resort can have (i.e. beach, ski, spa etc...). Each feature has got a primary key called id.
Table 3: is_i2f to connect each resort id with the feature id. This table has got 2 fields: id_i and id_f. Both fields are primary key.
I have created a form to insert a new resort, but I'm stuck here. I need a proper mysql query to insert a new resort in the is_main table and insert in is_i2f one record for each feature it has, with the id of the resort id id_i and the id of the feature id id_f.
$features = ['beach','relax','city_break','theme_park','ski','spa','views','fine_dining','golf'];
mysql_query("INSERT INTO is_main (inv_name, armchair, holiday, sipp, resort, price, rooms, inv_length, more_info)
VALUES ('$name', '$armchair', '$holiday', '$sipp', '$resort', '$price', '$rooms', '$length', '$more_info')");
$id = mysql_insert_id();
foreach($features as $feature) {
if(isset($_POST[$feature])) {
$$feature = 1;
mysql_query("INSERT INTO is_i2f (id_i, id_f) VALUES (" . $id . ", ?????????????? /missing part here????/ ); }
else {
$$feature = 0; }
}
Thanks.
Please, I'm going CrAzY!!!!!!!!!!!!!!
This may not be relevant to you, but...
Would it not make more sense to leave the link table unpopulated? You can use JOINs to then select what you need to populate the various views etc in your application
i.e. query to get 1 resort with all features:
SELECT
Id,
f.Id,
f.Name
FROM IS_MAIN m
CROSS JOIN IS_FEATURES f
WHERE m.Id = $RequiredResortId
Please find the answer on Mysql insert into 2 tables.
If you want to do multiple insert at a time you can write a SP to fulfill your needs
If I understand you correctly you could concatenate variable amount of to be inserted/selected values into one query. (This is the second query which needs an id from the first.)
//initializing variables
$id = mysql_insert_id();
$qTail = '';
$i = -1;
//standard beginning
$qHead = "INSERT INTO `is_i2f` (`id`,`feature`) VALUES ";
//loop through variable amount of variables
foreach($features] as $key => $feature) {
$i++;
//id stays the same, $feature varies
$qValues[$i] = "('{$id}', '{$feature}')";
//multiple values into one string
$qTail .= $qValues[$i] . ',';
} //end of foreach
//concatenate working query, need to remove last comma from $qTail
$q = $qHead . rtrim($qTail, ',');
Now you should have a usable insert query $q. Just echo it and see how it looks and test if it works.
Hope this was the case. If not, sorry...

Mysql search multipule value from comma seperated string

Here I want to search like
I have a string say $var = "1,3,5,7"
And
in my table say table student there is a column say column_abc
And this column contain values like
column_abc
2,3,45,6
1,3,4,5,8
3,4,6,9
1,5,10,13,34
I want to search $var against that column column_abc
can anybody help me
In result I want rows which contain any number present in $var
Am I right that you want to search in the table students for the value of column_abc? In that case you can use the following PHP code:
$result = mysql_query("SELECT * FROM `student` WHERE `column_abc` = '" . mysql_real_escape_string($var) . "'");
Hope this helped.
This solution may work for you ...
where column_abc regexp '(^|,)$var($|,)'
If $var is equal to 2, then it will find it twice in the below scenario:
2,3,45,6,12
1,2,3,4,5,8
3,4,6,9
1,5,10,13,34
EDIT: Just re-read your question, and you were looking for an entire string of numbers, and not just one ....
declare #search int(10)
declare #Search2 int(10)
Set #Search = '1,2,3,4'
Set #Search2 = #Search+'%'
select * from student where _abc like #Search2

How to insert Search Query into MYSQL - Check for Double Words

what is the best method to insert a search query into MySql
and check for double words? (for showing up the last searches and a collection of searches)
maybe something like this:
< ?php
/*------------------------------
Read and save the search query
-------------------------------*/
$querystat = mysql_real_escape_string($_GET['q']);
$insertquery = "INSERT INTO `query` ( `query`) VALUES ( '$querystat');";
mysql_query($insertquery, $db);
}
?>
but how to check for double words?
If you don't like a field to contain duplicated entries, you have to define it as UNIQUE.
Then you would issue your connands just the way you suggested:
$querystat = mysql_real_escape_string($_GET['q']);
$insertquery = "INSERT INTO `query` ( `query`) VALUES ( '$querystat');";
$res = mysql_query($insertquery, $db);
if (!$res) echo 'Insert faild. Most likely query already exists';