reuse of resource in another sql statement - php

i am using php with mySql server, pretty new to all the sql and i have a question:
i have a query:
$book_copy_user = "SELECT * FROM copy_book " .
"JOIN copy_user_own " .
"ON copy_book.copy_id = copy_user_own.copy_id " .
"WHERE copy_user_own.user_id=1";
$res1 =mysql_query($sql1) or die (mysql_error());
which returns something like
[{"copy_id":"1","book_id":"1","user_id":"1"},
{"copy_id":"2","book_id":"2","user_id":"1"},
{"copy_id":"3","book_id":"3","user_id":"1"},
{"copy_id":"4","book_id":"4","user_id":"1"}]
i would like to do 3 different select on the result with a where clause, but when trying to so it tells me that there is more the one column.
my question is:
is there a way that i can use the select result and apply select on it?
if so how can i relate to the fields of the in the select result?
please provide code samples
thanks you all you are saints :)

You can select the data into a temporary table and perform more queries on that table.
CREATE TEMPORARY TABLE temp_table SELECT ...
But I think it would be best if you posted your actual problem, it is very likely that there are much better solutions.

SELECT * FROM (SELECT * FROM copy_book JOIN copy_user_own ON copy_book.copy_id = copy_user_own.copy_id WHERE copy_user_own.user_id=1) WHERE copy_id = 4
althrough I'm not sure if it works in mysql.
No, after running select you cannot apply another on it.

Related

How to form the proper query

I am trying to form a query for MySQL where it gets all the info from multiple tables but only displays the ones where the "activity" = "Other". Right now it is displaying everyones info and I don't know the proper way to format the WHERE part of the query. I want it to access the jobSearch table, read the activity and only return the ones where the activity is "Other"
$query_student = " SELECT *
FROM student
JOIN major
ON student.studentID=major.studentID
JOIN jobSearch
ON major.studentID=jobSearch.studentID
WHERE jobSearch.activity == Other";
You SQL syntax is wrong, it should be:
SELECT * FROM table_name WHERE column = value
In your case:
SELECT * FROM student ... WHERE jobSearch.activity = 'Other'
For reference, check this good tutorial about SQL syntax: http://www.tutorialspoint.com/sql/sql-where-clause.htm
Your SQL syntax is OK is not wrong
SELECT *
FROM student
JOIN major ON student.studentID=major.studentID
JOIN jobSearch ON major.studentID=jobSearch.studentID
WHERE jobSearch.activity = 'Other';
If jobsearch.activity field is a varchar use single quotes around the word Other and use only one "=".
Also I recommend using alias and not using "Select *", you might run into a problem because you have the same field name in different tables, try to use something like this.
SELECT st.*, mj.field1, mj.field2, js.activity, js.field2
FROM student st
JOIN major mj ON st.studentID=mj.studentID
JOIN jobSearch js ON mj.studentID=js.studentID
WHERE js.activity = 'Other';

List of all tables used in MySQL query

I need the simplest way to get all table names used in MySQL query
"select * From Tab1 " $result= Tab1
"select * From Tab1, Tab2 Where ID1=ID2" $result= Tab1, Tab2
"delete From Tab1" $result= Tab1
You can use EXPLAIN for SELECT statements - simply prepend EXPLAIN keyword in front of your query and execute it. It will give you MySQL query execution plan, which will also include list of tables involved - check out this SQLFiddle.
It should also work For DELETE statements, but beware that it may actually delete rows as side effect, which may not be desirable for your task.
You can use php function mysql_info which return information about last query executed.
string mysql_info ([ resource $link_identifier = NULL ] )
i'm not completely sure about your intention but to list all tables from a database simply execute the following command
SHOW TABLES from 'dbname'

This query on mysql is taking forever to execute

im making a simple admin module to query the database to show the results. Im using this query via php:
SELECT
*
FROM myTable
WHERE id in(SELECT
id_registro
FROM myOtherTable
where id_forma='".$id_club."' and fecha_visita Like '%".$hoy."%'
)
order by id DESC
The result shows, however, it takes very long like 2 minutes..Anyone can help me out?
Thanks!
Without seeing your database, it is hard to find a way to make it faster.
Maybe you can try to turn your WHERE IN to INNER JOIN. To something like this
SELECT * FROM myTable INNER JOIN myOtherTable
ON (myTable.id = myOtherTable.id_registro)
WHERE myOtherTable.id_forma = '$id_club'
AND myOtherTable.fecha_visita LIKE '%$hoy%'
ORDER BY myTable.id DESC
Noted that you should sanitize your variable before putting it SQL query or using PDO prepare statement.
Sub Queries takes always time, so its better to ignore them as much as possible.
Try to optimize your query by checking its cardinality,possible keys getting implemented by DESC or EXPLAIN , and if necessary use FORCE INDEX over possible keys.
and I guess you can modify your query as:
SELECT
*
FROM myTable
inner join id_registro
on (id = id_forma )
where
id_forma='".$id_club."' and fecha_visita Like '%".$hoy."%'
order by id DESC
LIKE in mysql may take a long time ,with or without index.
Do u have a very large DB?

Mysql SELECT and UNION multiple tables with a similar name

I was wondering if it is possible to create a dynamic Union query for all tables with the same name but with a different number at the end. I have created a system but with each user having their own table such as:
user_table_$userID
I have achieved this in PHP but really would like to create a more dynamic code. I currently have 2-3 nested queries to grab the posts from each table without putting strain on the web server or database.
I suppose I could count the number of users in the user login table and create a for loop:
for ($i = 1; $i >= $usrCount; $i++)
{
$queryArray[] = "(SELECT post_title, post_description FROM user_table_" . $i . ") UNION";
}
But if the user count is a very large number the PHP script could take a long time to load. Is there any way I could get the Mysql database to create a dynamic query based on tables with the name like = "user_table_%"
If there are any suggestions please let me know.
Thank you.
Maybe it's better to normalize your database, but if you need a dynamic query you could use this:
SELECT
GROUP_CONCAT(
CONCAT(
'SELECT * FROM `',
TABLE_NAME,
'`') SEPARATOR ' UNION ALL ')
FROM
`INFORMATION_SCHEMA`.`TABLES`
WHERE
`TABLE_NAME` REGEXP '^user\_[0-9]*$'
INTO #sql;
PREPARE stmt FROM #sql;
EXECUTE stmt;
Please see fiddle here.
You can't and even if you find a clever hack you shouldn't.
Your best bet is to think again about your database schema. I assure you that your current structure is BAD, very very BAD. What if by chance you develop the new facebook? will you have ONE BILLION TABLES?
search for google about "database normalization" and "3rd normal form"
Seems like you should have only one table user_table containing a user_id field.
Now if you still want to keep your current model and need MySQL to build your query, maybe you could:
SHOW TABLES LIKE "user_table_%";
Create a temporary table and do INSERT SELECT for each table.
But again, it's barely advised to say the least
First normalized your table,for the time being you can run this query
SELECT post_title, post_description FROM (select table_name from INFORMATION_SCHEMA where table_name like 'user_table_%';
This should work fine (but consider "database normalization")
for ($i = 1; $i >= $usrCount; $i++){
$queryArray[$i] = "(SELECT post_title, post_description FROM user_table_".$i.")";
}
$sql = implode(' UNION ', $queryArray);
Dynamic queries are called Views in MySQL. These are virtual tables that contain the results from querying other tables and are persisted so survive a restart of the server. Here is an example of creating a view that contains the posts from all users:
CREATE OR REPLACE VIEW all_users.posts AS
SELECT * FROM user1.posts
UNION ALL
SELECT * FROM user2.posts;
Learn more here:
https://dev.mysql.com/doc/refman/8.0/en/views.html

Filtering SQL Queries Using PHP

I have been searching for a while on a way to select certain columns (fields) in SQL.
What I am trying to do is this... Lets say I have a table with 200 columns of data. I want to select an entire row but only the last 197 columns of data. Leaving out the first 3 columns that have dates and ID's.
It would be very time consuming to type out the 197 field names I wanted the data from. There has to be some easier way of doing it.
Any help or suggestions to point me in the correct direction?
If you are using MySQL, try something like this:
<?php
$query = "
SHOW COLUMNS FROM `Table`
WHERE `Field` NOT LIKE 'rowtoignore1'
AND `Field` NOT LIKE 'rowtoignore2'
AND `Field` NOT LIKE 'rowtoignore3'
";
$r = mysql_query($query) or die(mysql_error());
$queryfields = "";
while($f = mysql_fetch_assoc($r)) {
$queryfields .= "`{$f['Field']}`,";
}
$queryfields = substr($queryfields,0,strlen($queryfields)-1);
$query = "SELECT {$queryfields} FROM `Table` WHERE xyz";
?>
If you're using MySQL you can query the schema to get a column name by index, so you could use an iterative PHP routine to build your query, but it would require 197 select statements before you could run the one you really want. Messy and inefficient.
It seems simpler to do a SELECT * and then ignore the first three columns. If you use mysql_fetch_assoc() you can get the columns you want easily. Take a look at:
http://php.net/manual/en/function.mysql-fetch-array.php
If i am doing this task, i won't exclude the first 3 columns . If the 3 columns contains lengthy text / blob , then you could avoid, else better fetch those 200 columns .
Using this function mysql_list_fields() fetch fields corresponding to a table , and customize the select query to include required fields

Categories