Just the 1st and 2nd statment works. When it comes to the third and fourth one, no results can be seen on the database.
I checked the logs (centos x64) for both php and mariadb but no errors recorded. No exceptions thrown too in try/catch blocks.
DB::unprepared('
CREATE TABLE clone1 LIKE table1;
INSERT clone1 SELECT * FROM table1
WHERE field LIKE "'.$value.'%";
CREATE TABLE clone2 LIKE table2;
INSERT clone2 SELECT * FROM table2;
WHERE field LIKE "'.$value.'%";
CREATE TABLE clone3 LIKE table3;
INSERT clone3 SELECT * FROM table3;
WHERE field LIKE "'.$value.'%";
CREATE TABLE clone4 LIKE table4;
INSERT clone4 SELECT * FROM table4;
WHERE field LIKE "'.$value.'%";
');
Any ideas? Thanks in advance.
Easy answer: I removed the commas from the end of the insert rows, which was caused the query to stop before where statements.
Related
SELECT EXISTS
(SELECT * FROM table WHERE deleted_at IS NULL and the_date = '$the_date' AND company_name = '$company_name' AND purchase_country = '$p_country' AND lot = '$lot_no') AS numofrecords")
What is wrong with this mysql query?
It is still allowing duplicates inserts (1 out of 1000 records). Around 100 users making entries, so the traffic is not that big, I assume. I do not have access to the database metrics, so I can not be sure.
The EXISTS condition is use in a WHERE clause. In your case, the first select doesn't specify the table and the condition.
One example:
SELECT *
FROM customers
WHERE EXISTS (SELECT *
FROM order_details
WHERE customers.customer_id = order_details.customer_id);
Try to put your statement like this, and if it returns the data duplicated, just use a DISTINCT. (SELECT DISCTINCT * .....)
Another approach for you :
INSERT INTO your_table VALUES (SELECT * FROM table GROUP BY your_column_want_to_dupplicate);
The answer from #Nick gave the clues to solve the issue. Separated EXIST check and INSERT was not the best way. Two users were actually able to do INSERT, if one got 0. A single statement query with INSERT ... ON DUPLICATE KEY UPDATE... was the way to go.
I have two different Databases, names:
dbtest: Table 1
dbtest2: Table 2
I want to select all the data and new entries from dbtest Table 1 to dbtest2 Table 2.
I have tried this
$sqlfin = "INSERT INTO dbtest2.Table2 SELECT * FROM dbtest.Table1";
$resultfi = mysqli_query($db_conn, $sqlfin);
But no luck so far. How can I assure that new Records are insert into both table ? Any help would be appreciated?
lets try it in this format
INSERT INTO `dbtest2`.`Table2` SELECT * FROM `dbtest`.`Table1`
The following conditions hold for INSERT ... SELECT statements:
Specify IGNORE to ignore rows that would cause duplicate-key violations.
AUTO_INCREMENT columns work as usual.
To ensure that the binary log can be used to re-create the original tables, MySQL does not permit concurrent inserts for INSERT ... SELECT
statements (see Section 8.11.3, “Concurrent Inserts”).
To avoid ambiguous column reference problems when the SELECT and the INSERT refer to the same table, provide a unique alias for each
table used in the SELECT part, and qualify column names in that
part with the appropriate alias.
INSERT ... SELECT Syntax
Create Trigger: for adding new entries
CREATE TRIGGER copy_record BEFORE INSERT ON dbtest.Table1
FOR EACH ROW
BEGIN
INSERT INTO dbtest2.Table2 (first_name, last_name) VALUES (new.first_name, new.last_name);
END
trigger_event indicates the kind of operation that activates the
trigger. These trigger_event values are permitted:
INSERT: The trigger activates whenever a new row is inserted into the table; for example, through INSERT, LOAD DATA, and REPLACE
statements.
UPDATE: The trigger activates whenever a row is modified; for example, through UPDATE statements.
DELETE: The trigger activates whenever a row is deleted from the table; for example, through DELETE and REPLACE statements. DROP TABLE
and TRUNCATE TABLE statements on the table do not activate this
trigger, because they do not use DELETE. Dropping a partition does not
activate DELETE triggers, either.
CREATE TRIGGER Syntax
Try this query for your desired task :
Query First (Create Table exactly same like in old database, if you have not):
CREATE TABLE dbtest2.Table2 LIKE dbtest.Table1;
Query Second (Insert all data to newly created table) :
INSERT INTO dbtest2.Table2 SELECT * FROM dbtest.Table1;
Your query looks correct but will fail if the 2 tables have a different structure. Specify the columns to avoid it like:
INSERT INTO dbtest2.Table2 (2_col_1, 2_col_2) SELECT 1_col_1, 1_col_2 FROM dbtest.Table1
With PDO (kind of alternative answer, I don't know much for Mysqli):
You could connect to Mysql with PDO without giving a database name when working with multiple ones (but this isn't mandatory), like:
$db = new PDO( "mysql:host=" . $host . ";", $user, $password, $options );
Then write the Database names, tables and columns like when making a JOIN (as you did): separated by a .
// an example ..
$useDb = $db->query("INSERT INTO db_1.table1 (value_1, value_2) SELECT value_3, value_4 FROM db_2.table2 WHERE db_2.table2.id = 5");
(example tested and working fine)
INSERT INTO dbtest2 (
id,
name,
status )
SELECT id,
name,
'1'
FROM dbtest
ORDER BY id ASC
You can use INSERT...SELECT syntax. Note that you can quote '1' directly in the SELECT part.
Wondering if there's a way to get MySQL to return the column names when the query result returns no rows? The issue is that our system has multiple large queries sometimes:
SELECT * FROM table
SELECT table1.*, table2.field1, table2.field2
SELECT table1.field1 AS f1, SUM(table2.field1) AS f2
etc. So only way to get the column names when the returned result is empty, would be to parse the queries, and attempt to run a query on the information_schema table. Which is possible, but would be rather complex. Any ideas?
Some PHP interfaces for MySQL have a function for result set metadata, which should return information even for a result set with zero rows.
MySQLi has mysqli_stmt::result_metadata().
PDO has PDOStatement::getColumnMeta(), but it's labeled "experimental," which probably just means it's not well tested in all PDO drivers.
One technique that you can use is to create a view on the query and then query information_schema with the view name.
That is, something like this:
create view v_JustForColumns as
<your query here>;
select *
from information_schema.columns
where table_name = 'v_JustForColumns';
drop view v_JustForColumns;
Try the below one. Here replace the YOUR_SCHEMA with your actual schema name and YOUR_TABLENAME with your actual table name:
select column_name from information_schema.columns
where not exists(select * from YOUR_SCHEMA.YOUR_TABLENAME)
and table_name='YOUR_TABLENAME';
I'm trying to create a mysql table from the inner join between two other tables. I'm dealing with a database someone creates which has the following tables:
sitematrix_sites
sitematrix_databases
They are related by another table (I don't know why don't use a foreign key) called sitematrix_sites_databases which has the following fields:
site_id and database_id.
That's how the two tables relate. Now I'm trying to remove that to make my life easier, so I have:
mysql> CREATE TABLE result AS(select * from sitematrix_databases INNER JOIN site
matrix_site_databases ON sitematrix_site_databases.database_id = sitematrix_data
bases.database_id);
ERROR 1060 (42S21): Duplicate column name 'database_id'
However, I'm getting that error. Does someone know how can I merge the two tables without repeating the database_id field?
Thanks
Remove the * in your SELECT statement and actually list out the columns you want in your new table. For columns that appear in both original tables, name the table as well (e.g. sitematrix_databases.database_id).
Don't use * instead name each column and use aliases. For instance instead of sitematrix_database.database_id you can have alternativeName. Also you can pick and choose which columns you want this way as well.
In SQL Server, you can use "select into". This might be equivalent syntax for mySql:
http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-select-into-table.html
Unfortunately, it's a two commands (not just one):
http://www.tech-recipes.com/rx/1487/copy-an-existing-mysql-table-to-a-new-table/
CREATE TABLE recipes_new LIKE production.recipes; INSERT recipes_new SELECT * FROM production.recipes;
Instead of using SELECT * ... try SELECT database_id ...
MySQL does not like joining tables that have the same column name.
This SQL statement is used in PHP:
Insert into Table from AS Select * from Tabl1 where id='5'
Any clues to why it is not inserting values from Table1 to Table? User executes this statement to create a copy.
Remove the "FROM AS" and it should work. See http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-select-into-table.html
Remove from as:
Insert into Table (Select * from Tabl1 where id='5')
(and BTW why '5' and not just 5? Is id actually a string value?)