Relational Database simple search string - mysql

Hey guys,
This is a follow-up to a question that I asked earlier. It is my first time using a relational database and I need help with a quick search string to bring up desired results.
Background information: I'm making a database for my photo portfolio and want to be able to retrieve image links/data via their categories. Each image can be listed in multiple categories.
My database is set-up as follows :
TABLE tbl_images (image_id, image_title, image_location, image_descrip,image_url)
TABLE tbl_categories (category_id,category_name,category_descrip)
TABLE tbl_image_categories (image_id,category_id)
Where one of my images (image_id=1) has two categories (Desert [category_id=1] and Winter [category_id=2]). Which I defined in tbl_image_categories as 1,1 and 1,2.
I also have a few other images that I defined as Desert images [category_id=1].
How would I go about getting which images should be loaded based on the Desert Category?
I tried:
SELECT tbl_images.image_url
FROM tbl_images,
tbl_image_categories,
tbl_categories
WHERE tbl_categories.category_id = 1

Try this:
SELECT DISTINCT tbl_images.image_url
FROM tbl_images,
tbl_image_categories,
tbl_categories
WHERE chad_categories.category_id = 1 //category_id=1 for Desert
AND chad_images.image_id = chad_image_categories.image_id
AND chad_image_categories.category_id = chad_categories.category_id

Related

Need help Writing MySQL Queries (Alexamara Marina database)

I am trying to self-teach myself database management using Murach books, and I found these exercises online but I don't know where to start with the last two. I am using the Alexamara Marina database to complete the following exercises.
Create a query that displays the following for all boats: (1 row)
Total number of boats (name it: number_of_boats),
the maximum rental fee (name it: highest_rental_fee),
the shortest boat (name it: shortest boat)
Modify exercise 3 (the one above) to display the same information by marina rather than as a total of all boats. (2 rows)
I appreciate any help or tips!
EDIT: I am not sure how to attach the Alexamara database file so I am pasting it on pastebin so that everyone can run and create it.(see below)
Alexamara
Yeah I was having trouble with the site letting me paste the link on its own... Sorry
i don't know the structure of the database you're working with, you could get it by using
SHOW COLUMNS FROM boats
i am assuming that the database name is 'boats' and it contains the columns 'fee' and 'length'
SELECT
COUNT(*) AS nuber_of_boats,
MAX(fee) AS highest_rental_fee,
MIN(length) AS shortest_boat
FROM boats;
I am assuming that a boat corresponds to the marina_slip table
Total number of boats (name it: number_of_boats)
SELECT
COUNT(*) AS number_of_boats,
MAX(RentalFee) AS highest_rental_fee,
MIN(Length) AS shorted_boat
from MarinaSlip
Modify exercise 3 (the one above) to display the same information by marina rather than as a total of all boats. (2 rows)
SELECT
COUNT(*) AS number_of_boats,
MAX(RentalFee) AS highest_rental_fee,
MIN(Length) AS shorted_boat,
MarinaNum
from MarinaSlip
group by MarinaNum

Append string to another table in MySQL

I’ve got a problem selecting some things in my database.
I’ve got 1 database with a lot of tables, however I only use 2 with this specific task.
I have a Clothing table, and I need to import this in my new database. I have succesfully transferred a lot of data, but now I need to take 1 final small step into completing this. In my Clothing table I have a column called Youtube link, here I have a link with an Youtube link, this specific link, in this specific column, I want to append that to another table I have in the database, let’s call it new_clothing_table. I there have a description column called prod_desc and I want to append the Youtube link to that column.
But there is also another “problem”, it’s not that every product has a Youtube link, so things have to be filtered in order to not fuck things royally up. A advantage I have, I have in both tables a product_name, and these are all the same. So I want to transfer that specific Youtube link if it’s there (sometimes there is a 0 filled in or nothing, but I dont think it’s NULL because if I make a SELECT query where Youtube_link is null I get zero rows..)
So can someone help me out>?
mysql has an update-join construct you can use:
UPDATE new_clothing_table nct
JOIN clothing c ON c.product_name = nct.product_name AND
c.youtube_link != '0'
SET nct.description = CONCAT(nct.description, c.youtube_link)
EDIT:
To make sure this does what you want, you could first select the updated content in order to examine it:
SELECT nct.description AS old_description,
CONCAT(nct.description, c.youtube_link) AS new_description
FROM new_clothing_table nct
JOIN clothing c ON c.product_name = nct.product_name AND
c.youtube_link != '0'

MySQL Join not Producing Desired Results

I'm working on writing a snippet for ModX that will find all document with the specified TV set to a user submitted value.
Here is a description of the tables I'm working with.
http://wiki.modxcms.com/index.php/Template_Variable_Database_Tables
Here is my query:
SELECT contentid
FROM prefix_site_tmplvar_contentvalues
JOIN prefix_site_tmplvar_contentvalues
ON prefix_site_tmplvars.id = prefix_site_tmplvar_contentvalues.tmplvarid
WHERE value="Red"
Currently it's producing results such as this:
http://pastebin.com/mEJ1w2be
Where each document ID will have a new row in the results for each Template Variable. So, for 7455 in the example there will be one array for the color="red" one for material="wood" one for size="small". Which, makes it difficult if I want to find a product that is red, small, and made of wood.
Is there a way that I could join these tables so that I could get one row per product with the document id and a set of template variable with associate values—not all broken up?
try
GROUP BY contentid
this will smush all the rows with the same contentid together.

inner query of subqery returning multiple rows

I am not that experience in sql so please forgive if its not a good question to ask,but i researched around almost for 3-4 days but no able to solve.
My problem is i have a table which have multiple image names in it,so what i have to do is whoever is the follower of a particular user i have to get the imaged from this table,so one user there can be multiple followers,so i have to fetch the images posted by all the followers.
Here is the subquery code snippet i am using.
SELECT id,
outfit_image,
img_title,
description
FROM outfitpic_list r2
WHERE Email=ANY(SELECT being_followed
FROM follower_table
WHERE follower='test#gmail.com')
So the inner query here returns multiple values,for each value(being_followed) i have to fetch all the images and display it,but with this query each time i get only one image.I tried IN also but didnot work out.
Table structure:-
Outfitpic_list table
id|outfit_image|datetime|Email|image_title|description
Follower_table
bring_followed|follower
Please help,I am stuck..!!
Thank you..!!
I think your problem may be the = sign between "E-mail" and "Any". Try this statement:
SELECT
id,
outfit_image,
img_title,
description
FROM outfitpic_list r2
WHERE Email IN
(
SELECT being_followed
FROM follower_table
WHERE follower='test#gmail.com'
)
It's the same statement, without the = sign, and the ANY keyword replaced with IN. (I cleaned it up a little to make it more readable)

Stumbleupon type query

Wow, makes your head spin!
I am about to start a project, and although my mySql is OK, I can't get my head around what required for this:
I have a table of web addresses.
id,url
1,http://www.url1.com
2,http://www.url2.com
3,http://www.url3.com
4,http://www.url4.com
I have a table of users.
id,name
1,fred bloggs
2,john bloggs
3,amy bloggs
I have a table of categories.
id,name
1,science
2,tech
3,adult
4,stackoverflow
I have a table of categories the user likes as numerical ref relating to the category unique ref. For example:
user,category
1,4
1,6
1,7
1,10
2,3
2,4
3,5
.
.
.
I have a table of scores relating to each website address. When a user visits one of these sites and says they like it, it's stored like so:
url_ref,category
4,2
4,3
4,6
4,2
4,3
5,2
5,3
.
.
.
So based on the above data, URL 4 would score (in it's own right) as follows: 2=2 3=2 6=1
What I was hoping to do was pick out a random URL from over 2,000,000 records based on the current users interests.
So if the logged in user likes categories 1,2,3 then I would like to ORDER BY a score generated based on their interest.
If the logged in user likes categories 2 3 and 6 then the total score would be 5. However, if the current logged in user only like categories 2 and 6, the URL score would be 3. So the order by would be in context of the logged in users interests.
Think of stumbleupon.
I was thinking of using a set of VIEWS to help with sub queries.
I'm guessing that all 2,000,000 records will need to be looked at and based on the id of the url it will look to see what scores it has based on each selected category of the current user.
So we need to know the user ID and this gets passed into the query as a constant from the start.
Ain't got a clue!
Chris Denman
What I was hoping to do was pick out a random URL from over 2,000,000 records based on the current users interests.
This screams for predictive modeling, something you probably wouldn't be able to pull off in the database. Basically, you'd want to precalculate your score for a given interest (or more likely set of interests) / URL combination, and then query based on the precalculated values. You'd most likely be best off doing this in application code somewhere.
Since you're trying to guess whether a user will like or dislike a link based on what you know about them, Bayes seems like a good starting point (sorry for the wikipedia link, but without knowing your programming language this is probably the best place to start): Naive Bayes Classifier
edit
The basic idea here is that you continually run your precalculation process, and once you have enough data you can try to distill it to a simple formula that you can use in your query. As you collect more data, you continue to run the precalculation process and use the expanded results to refine your formula. This gets really interesting if you have the means to suggest a link, then find out whether the user liked it or not, as you can use this feedback loop really improve the prediction algorithm (have a read on machine learning, particularly genetic algorithms, for more on this)
I did this in the end:
$dbh = new NewSys::mySqlAccess("xxxxxxxxxx","xxxxxxxxxx","xxxxxxxxx","localhost");
$icat{1}='animals pets';
$icat{2}='gadget addict';
$icat{3}='games online play';
$icat{4}='painting art';
$icat{5}='graphic designer design';
$icat{6}='philosophy';
$icat{7}='strange unusual bizarre';
$icat{8}='health fitness';
$icat{9}='photography photographer';
$icat{10}='reading books';
$icat{11}='humour humor comedy comedian funny';
$icat{12}='psychology psychologist';
$icat{13}='cartoons cartoonist';
$icat{14}='internet technology';
$icat{15}='science scientist';
$icat{16}='clothing fashion';
$icat{17}='movies movie latest';
$icat{18}="\"self improvement\"";
$icat{19}='drawing art';
$icat{20}='latest band member';
$icat{21}='shop prices';
$icat{22}='recipe recipes food';
$icat{23}='mythology';
$icat{24}='holiday resorts destinations';
$icat{25}="(rude words)";
$icat{26}="www website";
$dbh->Sql("DELETE FROM precalc WHERE member = '$fdat{cred_id}'");
$dbh->Sql("SELECT * FROM prefs WHERE member = '$fdat{cred_id}'");
#chos=();
while($dbh->FetchRow()){
$cat=$dbh->Data('category');
$cats{$cat}='#';
}
foreach $cat (keys %cats){
push #chos,"\'$cat\'";
push #strings,$icat{$cat};
}
$sqll=join("\,",#chos);
$words=join(" ",#strings);
$dbh->Sql("select users.id,users.url,IFNULL((select sum(scoretot.scr) from scoretot where scoretot.id = users.id and scoretot.category IN \($sqll\)),0) as score from users WHERE MATCH (description,lasttweet) AGAINST ('$words' IN BOOLEAN MODE) AND IFNULL((SELECT ref FROM visited WHERE member = '$fdat{cred_id}' AND user = users.id LIMIT 1),0) = 0 ORDER BY score DESC limit 30");
$cnt=0;
while($dbh->FetchRow()){
$id=$dbh->Data('id');
$url=$dbh->Data('url');
$score=$dbh->Data('score');
$dbh2->Sql("INSERT INTO precalc (member,user,url,score) VALUES ('$fdat{cred_id}','$id','$url','$score')");
$cnt++;
}
I came up with this answer about three months ago, and just cannot read it. So sorry, I can't explain how it finally worked, but it managed to query 2 million websites and choose one based on the history of a users past votes on other sites.
Once I got it working, I moved on to another problem!
http://www.staggerupon.com is where it all happens!
Chris