I have a table of dictionary terms and now I would like to create another table which would hold ID of the 'main' term and ID of related terms that have the 'main' term's Name included in their Definition -
table: terms
| id | name | definition |
Table: related
| term_id | related_term_id |
It was pretty easy to create INSERT statements in PHP:
$result = mysql_query("SELECT * FROM terms");
while ($row = mysql_fetch_array($result)) {
$name = $row['name'];
$result2 = mysql_query("SELECT id,name FROM terms WHERE description LIKE \"%$name%\" AND id!=".$row['id']);
while ($row2 = mysql_fetch_array($result2)) {
echo "INSERT INTO related(term_id,related_term_id) VALUES(".$row['id'].",".$row2['id'].");";
}
}
However, as I don't have too much experience with MySQL I was wondering if that can be done purely in SQL - let say with use of INSERT-SELECT statement?
Thanks!
INSERT INTO related (term_id, related_term_id)
SELECT a.id as term_id, b.id AS related_term_id
FROM terms a, terms b
WHERE a.id != b.id
AND b.description LIKE CONCAT('%', b.name, '%')
It's going to be real slow if the terms table is big (more than 1000-10000 rows):
INSERT INTO related (term_id, related_term_id)
SELECT describing.id, described.id
FROM terms describing
JOIN terms described
ON CONCAT(' ', described.description, ' ') LIKE CONCAT('% ', describing.name, ' %')
Assuming all descriptions have spaces separating words and no other marks like , or ? or ! or . If that's not the case, the code will be more complicated.
Change your INSERT query:
echo "INSERT INTO related(term_id,related_term_id) VALUES('". $row['id'] ."','". $row2['id'] ."');";
Related
I have two different tables of the following structure:
grouprel
id | userId | pupID | groupId
pupils
id | userId | fname | lname
pupId in groulrel is equal to id in pupils.
I want to fetch pupils from a different group and then order them by fname, lname.
Now I have two queries like this:
$q = "SELECT * FROM grouprel WHERE userid = ". $userid ." AND groupId = ". $_GET['id'] ."";
$r = mysqli_query($mysqli, $q);
while ($rows = mysqli_fetch_object($r)) {
$query = "SELECT id, fname, lname FROM pupils WHERE userid = ". $userid ." AND id = ". $rows->pupId ." AND status = 0 ORDER BY fname, lname";
$result = mysqli_query($mysqli, $query);
while($row = mysqli_fetch_object($result)) {
echo stuff...
}
}
This works, but it doesn't order the names alphabetically like I want to.
How could I fix this?
This is iterating over the first query:
while ($rows = mysqli_fetch_object($r)) {
And this iterates over each instance of the second query:
while($row = mysqli_fetch_object($result)) {
So if the first query returns 1,2,3, and each iteration of the second query returns A,B, then your output would be:
1 A
1 B
2 A
2 B
3 A
3 B
The second query is ordering by the ORDER BY clause you gave it. But you are ordering the entire output by the first query.
Ultimately, why do you need these separate queries at all? Executing a database query in a loop is almost always the wrong idea. It looks like all you need is one query with a simple JOIN. Guessing on your logic, something like this:
SELECT
pupils.id, pupils.fname, pupils.lname
FROM
pupils
INNER JOIN grouprel ON pupils.id = grouprel.pupId
WHERE
pupils.userid = ?
AND grouprel.groupId = ?
AND pupils.status = 0
ORDER BY
fname, lname
It may take a little tweaking to match exactly what you're looking for, but you can achieve your goal with a single query instead of multiple separate queries. Then the results of that query will be ordered the way you told MySQL to order them, instead of the way you told PHP to order them.
I am working on a webpage that displays list of shops. I have 2 tables, shops and shops_sched.
+-shops-+
| id | title |
+-------------shops_sched-------------+
| id | shops_id | start_date | end_date |
Basically, the program displays the list of shops from the shops table, but if a value from shops.id is found # shops_sched.shops_id the page must output shops.title + 'coming soon'.
I understand this will be easy if I just place the date fields inside the table shops but due to programming restrictions I can't. I'm working on an existing project and I'm trying to minimize changes to existing functions. I can create new PHP functions if necessary though.
In addition, I need to get all the entries from the shops table. The Program needs to return all shops.title but for those shops whose id is found # shops_sched.shops_id, the program will have to return shops.title + "Coming Soon".
must output shops.title + 'coming soon'.
So do it like this:
$shops.title = "Donut-John";
echo $shops.title." coming soon";
To join the shops and shops_sched table
$query = SELECT `title` FROM `shops` JOIN `shops_sched` ON `shops`.`id` = `shops_sched`.`shops_id` WHERE `shops_sched`.`shop_id` = 5;
$result = mysql_query($query);
while($row = mysql_fetch_array($result) {
echo $row['title'] . 'coming soon';
}
For more about join you also can refer the following link
https://dev.mysql.com/doc/refman/5.0/en/join.html
http://www.tutorialspoint.com/mysql/mysql-using-joins.htm
Join the two tables :
SELECT shops.title
FROM shops INNER JOIN shops_sched ON shops.id = shops_sched.shops_id
The query should return only the the shops inside shops_sched
EDIT :
If I understood your question, try this :
SELECT shops.title, shops_sched.id
FROM shops LEFT JOIN shops_sched ON shops.id = shops_sched.shops_id
This will return all the titles, and the shops_sched.shops_id if shops.id = shops_sched.shops_id. In the other case, the hops_sched.shops_id will be null
Then you fetch the rows and if the second row is not null, print title + coming soon
Sample code : (Something like this)
$query = "SELECT `title`, 'shops_id' FROM `shops` LEFT JOIN `shops_sched` ON `shops`.`id` = `shops_sched`.`shops_id` WHERE `shops_sched`.`shop_id`";
$result = mysql_query($query);
while($row = mysql_fetch_array($result) {
if($row['shops_id'] != "")
{
echo $row['title'] . ' coming soon';
}
else
{
echo $row['title'];
}
}
i have 3 different queries like below:
$query = "select category_id,category_name from category";
$result = $this->Dbmodel->customQueryResult($query);
$query = "select location,location_name from sub_category";
$result_one = $this->Dbmodel->customQueryResult($query);
$query = "select category_date,category_month from other_category";
$result_two = $this->Dbmodel->customQueryResult($query);
here i am calling mysql server 3 times to execute my query and getting the result thereby..
now i am thinking how can i reduce mysql call so that all these 3 query gets executed in one single query so making only 1 call to mysql server and displaying all different results to user using php
how can i do this.. any help or suggestion would be a great help.. thanks in advance
What you've described is an SQL UNION.
Below is an example query you could use to achieve your goal:
SELECT category_id,category_name FROM category
UNION
SELECT location,location_name FROM sub_category
UNION
SELECT category_date,category_month FROM other_category
Example usage:
$query = 'SELECT category_id, category_name FROM category
UNION
SELECT location, location_name FROM sub_category
UNION
SELECT category_date, category_month FROM other_category';
$result = $this->Dbmodel->customQueryResult($query);
echo 'CategoryID: ' . $result['category_id'] . '<br />';
echo 'Category Name: ' . $result['category_name'] . '<br />';
echo 'Location: ' . $result['location'] . '<br />';
echo 'Location Name: ' . $result['location_name'] . '<br />';
echo 'Category Date: ' . $result['category_date'] . '<br />';
echo 'Category Month: ' . $result['category_month'];
Keep in mind, in case you need to select fields with identical names from different tables to use SQL aliases. An example of an alias:
SELECT category_id AS `catID` FROM category
Instead of $result['category_id'], you would use $result['catID'] instead.
As you are saying none of the tables are related, you have to fetch 3 queries.
You shouldn't combine queries, if there is no any relation. Otherwise it will give you ambiguous data.
We use sub-queries, joins when there is some relation to minimize queries.
Anyways you can get 3 queries result, if 1st, 2nd column have same data type and you can identify from 3rd column it's table name.
SELECT category_id,category_name, 'category' FROM category
UNION
SELECT location,location_name, 'sub_category' FROM sub_category
UNION
SELECT category_date,category_month, 'other_category' FROM other_category
THIS WILL BE EXACT QUERY
$query = "select category.category_id,category.category_name, sub_category.location,sub_category.location_name,other_category.category_date,other_category.category_month from category,sub_category,other_category";
You can use joint properties something like that.
$query = "select * from category, sub_category, other_category";
Note: on *, you can read this question MySQL - specific columns on join?
If the tables are related you could use joins. If that not the case you could use mysql UNION
It would be something like ...
$query = "select category_id,category_name from category UNION select location,location_name from sub_category UNION select category_date,category_month from other_category";
If all 3 Query have same data then we can Combine all 3 queries, Otherwise it would be not useful.
The Other way, Would be as Follows
Select c.category_id, c.category_name,
l.location,l.location_name,
o.category_date,o.category_month
from category C,
sub_category l,
other_category o
But Above would does get the Meaningful Data.
Im new in PHP and I have create a table (bookstore) really look like this
no_id | author | id_book | id_topic | quote | comments | no_page
id_book and id_topic have another table eg
table for book
:
id_book | book_name
table for topic
:
id_topic | topic_name
I made this sql statement for show the output in my system,but my problem is the system show only one output when submit a keyword. even though there are few similar word in the database.
"SELECT a.*, b.book_name
FROM bookstore AS a
LEFT JOIN book AS b ON a.id_book=b.id_book
WHERE quote LIKE '%".
can anyone help me how to show all match quote? i am so confuse *_*
Edit:
This is my php code.
$colname_Recordset1 = "-1";
if (isset($_GET['quote'])) {
$colname_Recordset1 = $_GET['quote'];
}
mysql_select_db($database_config, $config);
$query_Recordset1 = "SELECT a.*, b.book_name FROM bookstore a
LEFT OUTER JOIN book b ON a.id_book = b.id_book
WHERE a.quote LIKE '%'". $colname_Recordset1."%%'";
$Recordset1 = mysql_query($query_Recordset1, $config)
or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
I think, if I understand correctly, that your query should be more like:
SELECT a.*, b.book_name
FROM bookstore a
LEFT OUTER JOIN book b ON a.id_book = b.id_book
WHERE a.quote LIKE '%'
If you are still getting a single result (where you know there is more than one result), you need to post the PHP code you are using to extract records from the DB.
You should fetch the result like this, reference http://www.php.net/manual/en/function.mysql-fetch-assoc.php
while ($row = mysql_fetch_assoc($Recordset1)) {
print_r($row);
}
and you should escape the user input with mysql_escape_string, the full php code
mysql_select_db($database_config, $config);
$filter = '';
if (isset($_GET['quote'])) {
$filter = " WHERE a.quote LIKE '%" . mysql_escape_string($_GET['quote']) . "%'";
}
$result = mysql_query(
"SELECT a.*, b.book_name FROM bookstore a
LEFT OUTER JOIN book b ON a.id_book = b.id_book" . $filter,
$config
) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
// If you need to output table, put the code here
print_r($row);
}
It's common to use ID and parent to store the categories tree. In my case, a knowledge base, in article table every record(article) belong to a category(with a field catid), in categories table every record has a ID and parent to save the tree structure.
article table
id | catid | date | subject | content
categories table
id | name | parent
The problem is when export article to csv or excel,
id | category | date | subject | content
how to keep the whole categories tree, just like when a article belong to son category, I want the category like
grandpa/father/son/, or grandpa : father : son
then can open the csv in excel, menu -> data -> text to column, seperate by ":", you will get a whole tree category not only current category.
work code sample:
$query = 'SELECT `a`.`id` AS `ID`, concat(CASE WHEN ISNULL(`f`.`name`) THEN "" ELSE concat(`f`.`name`,":") END,CASE WHEN ISNULL(`e`.`name`) THEN "" ELSE concat(`e`.`name`,":") END,CASE WHEN ISNULL(`d`.`name`) THEN "" ELSE concat(`d`.`name`,":") END,CASE WHEN ISNULL(`c`.`name`) THEN "" ELSE concat(`c`.`name`,":") END,CASE WHEN ISNULL(`b`.`name`) THEN "" ELSE `b`.`name` END) AS `Category`, `a`.`subject` AS `Subject`,`a`.`content` AS `Content`,`a`.`dt` AS `Date Created`,
FROM articles as a
LEFT JOIN categories as b ON a.catid = b.id
LEFT JOIN categories as c ON b.parent = c.id
LEFT JOIN categories as d ON c.parent = d.id
LEFT JOIN categories as e ON d.parent = e.id
LEFT JOIN categories as f ON e.parent = f.id
WHERE (DATE(`dt`) BETWEEN \'' . $date_from . '\' AND \'' . $date_to . '\') order by id asc';
hope it help for others which want to export tree structure fields.
You have to parse the result after querying the database:
$query = 'query code here';
$result = mysql_query($query);
while( $row = mysql_fetch_array($result) ) {
// do something with that row
}
Besides, mysql_x functions are deprecated. Use PDO or mysqli instead.
<?php
$conn = mysql_connect("localhost","YOUR DB USER NAME","YOUR DB PASSWORD");
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("YOUR DB NAME", $conn);
$result = mysql_query("YOUR QUERY HERE");
while($row = mysql_fetch_array($result)) {
echo $row['ID'];
-----
-----
}
mysql_close($conn);
I assume, you would like to execute the SQL code in PHP, that you designed in phpMyAdmin - which works well. The most common problems are with the quotes. Learn about String quotes here
As I see you use ' to frame the query code, but you use it inside the query as well. That must have produced an awful series of syntax errors. You may use " to frame the query code while setting it to a variable.
If you get nothing, than maybe the SQL command could have executed, but the result was empty. You can test this with the var_dump() function. Also check that you have all the error reporting switched on. Learn about error reporting here
Also, I'd suggest you to examine and use the PDO class instead of the mysql functions, which would throw you handsome exceptions you could catch and deal with the errors elegantly. The PDO
will also secure your code in some way.