i have a bunch of tables in one database. i am using three for testing and have created the following sqls
SELECT DISTINCT bb_users.user_nickname FROM bb_users
JOIN bucket_list ON bb_users.username = bucket_list.author
WHERE bucket_list.status=(:s) ORDER BY bucket_list.author ASC LIMIT 0, 30
This returns the user_nickname from the bb_users table and works as expected
I then use the following to do so on a table named music
SELECT DISTINCT bb_users.user_nickname FROM bb_users
JOIN music ON bb_users.username = music.author
WHERE music.status=(:s) ORDER BY music.author ASC LIMIT 0, 30
i run the sql query with the prepared statement:
//$sql ->the sql statements from above
$prep=$conn->prepare($sql);
$exec=$prep->execute(array(":s"=>"active")); var_dump($exec);
while($fetch=$prep->fetch(PDO::FETCH_ASSOC)){
//do stuff
}
the music tables outputs nothing and using php PDO the execute method returns false
both of these lines of code are dynamically created so i am very confused as to how one works and the other does not
any help is greatly appreciated
Changed the collation code from utf8_unicode_ci to utf8_general_ci
Related
For adding database I am using PhpMyAdmin in Xampp server. I have created two tables and each table contains different rows. I am trying to select values from two tables at the same time in php. The following code works fine
$gi1=2;
$stmt2=$this->con->prepare(" SELECT qwer FROM table1 WHERE nmnm=?;");
$stmt2->bind_param("i",$gi1);
$stmt2->execute();
$stmt2->bind_result($var1);
$stmt2->fetch();
$gi2=23;
$stmt2=$this->con->prepare(" SELECT qwer2 FROM table2 WHERE nmnm2=?;");
$stmt2->bind_param("i",$gi2);
$stmt2->execute();
$stmt2->bind_result($var2);
$stmt2->fetch();
But it takes too much time so I decided it to select in one statement.
$gi2=23;$gi1=2;
$stmt2=$this->con->prepare(" SELECT qwer2,qwer1 FROM table2,table1 WHERE nmnm2=? or nmnm=?;");
$stmt2->bind_param("ii",$gi2,$gi1);
$stmt2->execute();
$stmt2->bind_result($var2,$var1);
$stmt2->fetch();
And it shows a fatal error.So how can I select values from two tables in one statement?
if the tables do not have any link columns you can try with UNION
SELECT qwer FROM table1 WHERE nmnm=?
union
(SELECT qwer2 as qwer FROM table2 WHERE nmnm2=?)
I'm using PHP with Mysqli and I'm trying to avoid duplicated results from the Database. However, the count result is different from these two very similar code. I'ts the first time I'm using DISTINCT, so I would like to know what's causing the difference. Thank you!
Ps: I saw similar question but the sql command is different.
Count: 83
SELECT DISTINCT (`email`) `id`,`name`,`email`,`sent`,`datasent`
FROM $dbtable_requests
WHERE `datasent`>'$datedb'
AND category = '$cat'
ORDER BY `name`
Count: 77
SELECT DISTINCT (`email`) `id`
FROM $dbtable_requests
WHERE `datasent`>'$datedb'
AND category='$cat_q'
Hi i'm writing a query that uses an insert and an update the update has a subquery which selects one or multiple rows.
When I run the query I get the following error: "#1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery"
The strange thing is that I am using the latest version of mysql and this feature was supported since 5.1. My query is as follows:
INSERT INTO Orders
(OrderID, Orderdate, Leverdate, status)
VALUES ('', now(), '2014-21-05', 'In Behandeling');
UPDATE Dozen SET OrderID = LAST_INSERT_ID()
WHERE OrderID IN (SELECT DoosID FROM Dozen Limit 0,3);
How can I rewrite this query to something mysql will understand and execute?
Thanks in advance!
use INNER JOIN
UPDATE Dozen
INNER JOIN Orders ON DoosID = OrderID
SET Dozen.OrderID = LAST_INSERT_ID()
Or change IN into = since your subquery anyways returns 1 record.
UPDATE Dozen
SET OrderID = LAST_INSERT_ID()
WHERE OrderID = (SELECT DoosID FROM Dozen LIMIT 1)
I am trying to write a dual MySQL query which archives the content of a table to another table, then deletes the original row in the original table.
I have the base query working just fine in other areas. The query below relies on a second table to help select which rows need to be archived & deleted.
I am getting a syntax error where the AS appears in the nested select of the first query and near the AS in the delete query.
I have researched and researched and tried a bunch of different code combos, but I can't get the queries working. The queries are written in PHP using PDO, so please ignore the PDO tags, they are not the problem.
INSERT INTO usetwca (r_id, c_id, o_id, t_id, s_id, ip_address, timestamp, timestamp_archived) SELECT :r_id, usetwc.c_id, usetwc.o_id, usetwc.t_id, usetwc.s_id, usetwc.ip_address, usetwc.timestamp, :timestamp FROM usetwc JOIN useo ON useo.o_id = usetwc.o_id AND useo.best_fit IS NULL WHERE usetwc.user_id = :user_id;
DELETE FROM usetwc JOIN useo ON useo.o_id = usetwc.o_id AND useo.best_fit IS NULL WHERE usetwc.user_id = :user_id;
You should implement this as a BEFORE DELETE trigger on the `users_sessions_exercise_t_ws_correlation' table.
Have a look at this answer as a good example.
Here's a good general reference on using Triggers for Logging.
I was able to get my queries working.
INSERT INTO usetwca (r_id, c_id, o_id, t_id, s_id, ip_address, timestamp, timestamp_archived) SELECT :r_id, usetwc.c_id, usetwc.o_id, usetwc.t_id, usetwc.s_id, usetwc.ip_address, usetwc.timestamp, :timestamp FROM usetwc JOIN useo ON useo.o_id = usetwc.o_id AND useo.best_fit IS NULL WHERE usetwc.user_id = :user_id;
DELETE usetwc FROM usetwc INNER JOIN useo ON useo.o_id = usetwc.o_id AND useo.best_fit IS NULL WHERE usetwc.user_id = :user_id
I'm getting a weird result from a quite long query, which I will simplify here:
DROP TEMPORARY TABLE IF EXISTS table1;
CREATE TEMPORARY TABLE table1 AS
(SELECT
parent.id as parent_id,
times.a_time,
times.sequence,
FROM times
LEFT JOIN parent ON times.parent_id=parent.id
WHERE times.stop_id=10);
DROP TEMPORARY TABLE IF EXISTS table2;
CREATE TEMPORARY TABLE table2 AS
(SELECT
parent.id as parent_id,
times.b_time,
times.sequence,
FROM times
LEFT JOIN parent ON times.parent_id=parent.id
WHERE times.stop_id=15 );
--here comes PDO->exec();
SELECT table1.*, table2.b_time
FROM table1
LEFT JOIN table2 ON table1.parent_id=table2.parent_id
WHERE table2.parent_id IS NOT NULL AND table1.sequence<table2.sequence
ORDER BY table1.a_time
I'm testing the query using EMS MySQL Manager 2007, and in PHP I'm using PDO query.
In order to get the final result, (I know that PDO doesn't support running this full query at once and giving back the result set), I run PDO->exec() after temporary tables creation (see comment in the query), and then I run PDO->query() on the last SELECT:
$db = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$tempTablesSQL='DROP TEMPORARY TABLE IF EXISTS...'; //create temporary tables
$db->exec($tempTablesSQL);
$sql='SELECT table1.*, table2.b_time ...'; //JOIN and SELECT the results
$results=array();
foreach($db->query($sql) as $row){
$results[]=$row;
}
print_r($results);
In MySQL Manager I run the whole query at once, and for those specific IDs I'm getting 29 rows as result (which is correct, because the records are inserted from a previously parsed file, and by comparing the results to the file I know they are good).
But in PHP, I'm getting only 25 results, and totally wrong values for b_time.
So, my questions are:
why do I get wrong results?
is my approach of calling this query wrong (in PHP)?
Any help is appreciated.
--EDIT--
It's not just PDO, I tried with mysqli_multi_query, I'm getting the same wrong results.
One important thing I noticed is: if I use regular tables instead of the temporary, the results are fine.
Let my try to put a couple of suggestions on the second part of your question which is is my approach of calling this query wrong?
First of all it looks like you don't need to create any temp tables. Based on what you showed the whole thing can be a single query like
SELECT q1.parent_id, q1.a_time, q1.sequence, q2.b_time
FROM
(
SELECT p.id parent_id, t.a_time, t.sequence
FROM times t LEFT JOIN parent p
ON t.parent_id=p.id
WHERE t.stop_id = ?
) q1 LEFT JOIN
(
SELECT p.id as parent_id, t.b_time, t.sequence
FROM times t LEFT JOIN parent p
ON t.parent_id=parent.id
WHERE t.stop_id = ?
) q2 ON q2.parent_id IS NOT NULL
AND q1.sequence < q2.sequence
ORDER BY q1.a_time
And execute it as a prepared statement
...
$sql = 'SELECT ...'; // the whole thing from above
$query = $db->prepare($sql);
$query->execute(array($stop_id1, $stop_id2));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);
Now even if for some reason you have to use temp tables and perform some manipulations along the way before returning the result set then I'd suggest to wrap it up a stored procedure
DELIMITER $$
CREATE PROCEDURE sp_myproc (IN stop_id1 INT, IN stop_id2 INT, ...)
BEGIN
DROP TEMPORARY TABLE IF EXISTS table1;
CREATE TEMPORARY TABLE table1 AS
...
WHERE times.stop_id = stop_id1;
DROP TEMPORARY TABLE IF EXISTS table1;
CREATE TEMPORARY TABLE table1 AS
...
WHERE times.stop_id = stop_id2
-- return the resultset
SELECT table1.*, table2.b_time
FROM table1
...
END$$
DELIMITER ;
And call your procedure once from php
...
$sql = 'CALL sp_myproc(?, ?)';
$query = $db->prepare($sql);
$query->execute(array($stop_id1, $stop_id2));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);
Now regarding the first part of your question why do I get wrong results? OUTER joins can be tricky and especially when you chain them. You can easily filter some rows out or produce additional rows (which happens most often).
Those few joins that you removed may be the cause.
Anyway provided information is not enough for conclusive answer.
But I would suggest instead of returning columns as table1.* specify all columns explicitly and give explicit aliases for columns that have the same names in different tables that are part of a join.