Run SQL Update Query on basis on SELECT query result (MySQL) - php

Good Afternoon All,
I'm currently mid-migration from an MS Access DB to a MySQL DB. Originally we had a field which was a multiple-select drop down list in Outlook, so the "Category" field contains multiple values and string values at that, which even with my best DBA hat on I know won't work.
What I'm trying to do is write a load of migration scripts effectively, so for starters write a select query:
SELECT * FROM tbl_clients where category like "%Newsletter%"
Then, I want to take the results of that, and almost in a do... while fashion, for each result run something like
SQL CREATE in table tbl_Client_Category_Assoc where ClientID is tbl_Clients.ClientID and Where CategoryID is 1
Please could anyone offer any assistance?
Many Thanks

Related

MySQL use view to access table under different name

I have a performance and best-practice question concerning mysql tables.
I´m working on an application which connects to a database which gets filled by other programms.
This system is deployed in differnet locations, and from location to location the name of some databases-tables can change (but the fields in this tables etc stay the same).
As I don´t want to change all sql querys in my application for every location, I thought about creating a mysql view which simply mirrors the contents of this table to the normaly used table-name.
Is this a suitable solution, or could it get awfully slow with big tables?
Simple views (created as SELECT * FROM table) behave like the specified table performance wise.
It should be a suitable solution for your case.
mmm, this is tricky. If there are multiple tables then a quick and dirty version for this would be something like
SELECT * FROM (SELECT * FROM table1
Union
SELECT * FROM table2
Union
SELECT * FROM table3) t
Which I think will work. You will of course have problems with pagination, sorting and searching - because you will have to try and do this over 3 or more tables.
Another way would be this
Create a table with the table names and a counter
ImportTable
name
id
Now in this you can enter the names of the tables and the last id that you want to import from.
Create another table to import the records
TableRecords
source
id
field1
field2
etc
Now run something that goes through the tables in ImportTable grabs any new records and shoves them into `TableRecords.
Now this becomes really simply you can query TableRecords and have pagination sorting and searching with no of the previous troubles.
Make something that runs this every 2 minutes say so TableRecords will be 2 mins behind but everything will be really easy and run like a dream.

MySQL 5.7.9 fulltext research in multiple tables with Sphinx on WAMP

I I have to do a research in multiple MySQL tables for my internship.
In fact, I do this for a web phone directory. I have a form text input to enter the research.
I tried to use the MATCH/AGAINST syntax but it appears to be wrong.
My query is actually that one :
SELECT U_ID, 'users'
from users
where match ([columns that I want to search in]) AGAINST ([The text inside my search field])
UNION
SELECT S_ID, 'service'
from service
where match ([columns that I want to search in]) AGAINST ([The text inside my search field])
This problem is the following : With this type of search, I must send the variable in many MATCH so I can't have a relevant result (because of the multiple against elements). The perfect solution could be to replace the 'UNION' by an 'INTER' but It would be too easy.
I don't know if it will be usefull, but I use PDO to send my query with PhP
I tried to search solutions but I couldn't find one for me :
https://dev.mysql.com/doc/refman/5.5/en/fulltext-search.html
Using Full-Text Search in SQL Server 2008 across multiple tables, columns
MySQL fulltext search on multiple tables with different fields
Then I tried to use Sphinx but the documentation is complicated to me and I couldn't understand it (http://sphinxsearch.com/docs/current.html).
Can someone help me to find the query that I need or can you give me a link of a very clear and simple Sphinx tutorial on Windows (I have read the IBM one) ?
Edit :
I wanted to illustrate my problem with the set theory (inter mean intersection).
For example, when I type "John accounting department" in my form input, I want to display all users named John, but only if they belong to the accounting department.
With my actual search, I will have the id of all the departments named : "John" or "accounting" or "department" and all the id for the people named "John" or accounting" or department".
That's my actual problem.
I think a materialized view would be the easiest way to solve this in MySQL.
They not strictly a feature of mysql (ie mysql cant maintain the view automatically, its not really a view) its a normal table, that just happens to be a copy of other table(s) data.
Can actually be created quite easily...
CREATE TABLE my_search_view (fulltext(U_Name,S_Name))
SELECT U_ID, U_Name, S_ID, S_Name
FROM user
INNER JOIN service USING (S_ID);
(If you update the source tables, just delete the table, and recreate it! Although can use triggers if want a more dynamic solution, but depending size of data it possibly not worth the effort)
Now you can just run a simply query against this table (it has a full-text index)
SELECT *
FROM my_search_view
WHERE MATCH (U_Name,S_Name) AGAINST ('John accounting department')

PHP MySQL advanced filtering

For a new version of a website, I am making a "Top User" section on the homepage. This allows people to vote for the user on a bunch of different categories. All this information is stored in a MySQL database in two main tables. One table has the information(id*autogenerated*, Username, Date added, etc.) and the other has the rates (id*autogenerated*, linkID, rowAvg, avg, avg2, etc.). The linkID from the rate table corresponds to the id from the information table. How the query works is it queries through the rate_table, orders it by highest averages then selects the first 10 results. Then using the linkID of that row, I select the actual information for that user from the info_table. This is fine and dandy as long as each user only has 1 rate. What happens when a user has 2 or more rates, and both of the rates are positive, is the query selects both of those and pulls the information for each of the 2 rows which is then displayed as two different users even though it is the same person. How can I make the rate_table query know when there are multiple rates for the same linkID and average them together instead of showing them as two different people. I was thinking of inserting each linkID into an array, then for each subsequently selected row, check if that linkID is already in the array. If not, insert it, if it is, then average them together and store it in the array and use the array to populate the table on the homepage. I feel like I am overthinking this. Sorry if this is a little confusing. If you need more information, let me know.
P.S. I'm still learning my way around MySQL queries so I apologize if I am going about this the completely wrong way and you spent the last few minutes trying to understand what I was saying :P
P.P.S. I know I shouldn't be using MySQL_Query anymore, and should be doing prepared statements. I want to master MySQL queries because that is what FMDB databases for iOS use then I will move onto learning prepared statements.
Take a look at some of the MySQL Aggregate Functions.
AVG() may be what you're looking for. The average of one result is just that result, so that should still work. Use the GROUP BY clause on the column that should be unique in order to run the aggregate calculation on the grouped rows.

Combining different table queries in db with PHP and displaying all results on one page

I have been trying to create a database for fun to get a better understanding of databases and using PHP to query them for a website I'm messing around with. Pretty much I have one database with 4 tables when a user enters a search term in a PHP search box my code searches the database for any entries containing the search term. Now I can easily get my code to search individual tables, but I cannot seem to get it to search all 4 tables and display the results on the same page.
info: making a database for skyrim
Table names: classes, powers, skills, shouts
column names: name, information
Here is a snippet of the code I have that works so far:
$raw_results = mysql_query("
SELECT *
FROM `xaviorin_skyrim`.`shouts` , `xaviorin_skyrim`.`classes`
WHERE (CONVERT(`UID` USING utf8) LIKE '%".$query."%' OR
CONVERT(`Name` USING utf8) LIKE '%".$query."%' OR
CONVERT(`Information` USING utf8) LIKE '%".$query."%')
") or die(mysql_error());`
Literally all I thought I would need to do is change the table name from "shouts" to say "classes" in a new raw_results line of code but that didn't work. I have attempted unions and joins and either keep screwing them up or just don't understand how to properly format them.
echo "<p><h3>".$results['Name']."</h3>".$results['Information']."</p>";
The code above this text is what displays the results on the page on my website... it works but I don't know how to combine the information from all 4 tables into one page. If I'm going about this in the wrong way and anyone can point me in the right direction I would GREATLY appreciate it... I've been trying to research the problem without finding a proper answer for near a month now.
The problem with your approach is that relational databases do a cross join when there are several query results from two different tables. So basically every match in one table will be combined with every match from the second table. When you have 3 entries in the first and 4 in the second table, you will get 3 * 4 = 12 entries in your query result. If you add more tables, you get even more results. You want to do a full text search in several tables that are totally unrelated, thus creating some kind of non-existing relation via cross joining them will not be useful.
What you actually want to do is a UNION ALL (UNION is slower because it prunes duplicates) of several queries:
SELECT name, information, 'shouts' AS tablename FROM shouts WHERE ...
UNION ALL
SELECT name, information, 'classes' AS tablename FROM classes WHERE ...
This will do search queries on every single table and then place the results in a single result. Also note that I added a third column to each query to ensure that the originating table is not lost after merging the results.
Unless you need to do some sorting afterwards, I would suggest that you do all statements separately. Combining them this way will most likely make the post-processing more complex. And several single queries will also be faster than one big query with UNION statements.
And as I mentioned in the comments: Don't use mysql_* functions!

Suitable design for a database application

I have a question related to a web app that I developed in PHP, MYSQL.
basically part 1 is :
I display results in the form of table say for software testing.
ID Prod_Name Set Date Result Platform
1 Alpha1 Pro1 01.01.01 PASS 2.3.1.2_OS
Now, I have divided the tables accordingly
Table Name: Results
ID, Name, Date, Result
Table Name : Set
ID, Set_Name, Prod_name
Table Name : Platform
ID, Platform_Name, Set_Name
Now, ID in each table is an incremented value and does not relate to anything else.
My php app, starts with fetching the results from 'Results' table. Since I want SET to be displayed for every row, I am making an another connection to the database and using the query
select Set_name
from Set
where Prod_name = row['Name'] // row['Name'] is fetched from the results table.
now I also want to display platform which I am extracting it from Platform table using the above method i.e making another connection and passing Set_Name = row['Set_Name'] from the Set table.
Now for my application is there any other way to achieve the same result ?
Typically, for large web based applications, if data is coming from a database server is making multiple connection to a DB server a feasible option?
Please do not consider the fact that with MySQL declaring a connection statement once will do the needful but what about MSSQL server? Do we need to write a long sql statement with several joins/selfjoins/unions and use those variables all over the application?
How is the application design for this case will be?
Can anyonce give me some ideas please?
Thanks.
For pretty much any flavour of database, a single SELECT statement which joins three tables will perform better than three separate statements querying a table apiece. Joining is what relational databases do.
I may not have understood everything, but here is something similar. First, let's make an ER model.
Now, because you don't seem to like joins, create a view in the database.
CREATE VIEW v_test AS
SELECT TestID, ProductName, TestName, Date, Result, PlatformName
FROM Product AS p
JOIN Test AS t ON t.ProductID = p.ProductID
JOIN Platform AS f ON f.PlatformID = t.PlatformID;
With this in place, you can simply use:
SELECT * FROM v_test WHERE ProductName = 'Alpha1'
You may also take a look at this question/answer with a similar scenario.

Categories