473,774 Members | 2,191 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

mysql/php query

I have a question about (i think) joining.

If I have a table in a database that has this info:

key - name - favorite
1 - john - 2
2 - judy - 3
3 - joe - 1

the favorite icecream table is this:
key - flavors
1 - vanilla
2 - chocolate
3 - strawberry

how do i do a query to display that judy's favorite is strawberry.

obviously this is a simple example. i am doing working on something
that is much more complex than this, but if anyone can give a hint i
can apply to the thing i am working on.

Thanks in advance!
Jul 17 '05 #1
13 5557

On 17-Nov-2003, re*********@msn .com (aaron) wrote:
I have a question about (i think) joining.

If I have a table in a database that has this info:

key - name - favorite
1 - john - 2
2 - judy - 3
3 - joe - 1

the favorite icecream table is this:
key - flavors
1 - vanilla
2 - chocolate
3 - strawberry

how do i do a query to display that judy's favorite is strawberry.

obviously this is a simple example. i am doing working on something
that is much more complex than this, but if anyone can give a hint i
can apply to the thing i am working on.


select flavors from nametable,icecr eamtable where favorite=icecre amtable.key
and name='judy'

--
Tom Thackrey
www.creative-light.com
tom (at) creative (dash) light (dot) com
do NOT send email to ja*********@wil lglen.net (it's reserved for spammers)
Jul 17 '05 #2
aaron, doing a poor impression of Xerex, said:

I have a question about (i think) joining.
This is really more of an SQL question than a PHP question.

If I have a table in a database that has this info:
key - name - favorite
the favorite icecream table is this:
key - flavor


Here's TFM: http://www.mysql.com/doc/en/JOIN.html

Here's your simple answer, since I'm not a complete asshole (and also I
personally find it easier to learn from example):

$q = mysql_query("SE LECT * FROM people
LEFT JOIN favorites
ON people.favorite = favorites.key
WHERE name = 'judy'");
if(!$q) die("query failed\n");
if(!mysql_num_r ows($q)) die("no entry for judy\n");
$rec = mysql_fetch_ass oc($q);
echo "judy's favorite is $rec[flavor]\n";

/joe
--
In git.talk.flame, Dr. Esque mentally reviles in Scott Hughes and a
processor, and then often links to the website of /home/pr0n and mcct and
hoovers, downloads, scans, and carefully emasculates Marilyn. The ninja
clan from icer will go to Irwin! In the Masquerade, Crai... [tape runs out]
Jul 17 '05 #3
*** aaron wrote/escribió (17 Nov 2003 08:49:53 -0800):
I have a question about (i think) joining.

If I have a table in a database that has this info:

key - name - favorite
1 - john - 2
2 - judy - 3
3 - joe - 1

the favorite icecream table is this:
key - flavors
1 - vanilla
2 - chocolate
3 - strawberry

how do i do a query to display that judy's favorite is strawberry.


Under MySQL you have two ways:

SELECT name, favourite
FROM people, flavours
WHERE favourite=flavo urs.key AND name='judy'

or

SELECT name, favourite
FROM people
INNER JOIN flavours ON favorite=flavou rs.key
WHERE name='judy'

Second one is more standard.

(Untested so typos expected)

--
--
-- Álvaro G. Vicario - Burgos, Spain
--
Jul 17 '05 #4
re*********@msn .com (aaron) schrieb:
If I have a table in a database that has this info:

key - name - favorite
1 - john - 2
2 - judy - 3
3 - joe - 1

the favorite icecream table is this:
key - flavors
1 - vanilla
2 - chocolate
3 - strawberry

how do i do a query to display that judy's favorite is strawberry.


SELECT icecream.flavor
FROM person, icecream
WHERE person.name = 'judy'
AND person.favorite = icecream.key

Regards,
Matthias
Jul 17 '05 #5
I noticed that Message-ID:
<dd************ ************@po sting.google.co m> from aaron contained the
following:
key - name - favorite
1 - john - 2
2 - judy - 3
3 - joe - 1

the favorite icecream table is this:
key - flavors
1 - vanilla
2 - chocolate
3 - strawberry

how do i do a query to display that judy's favorite is strawberry.


SELECT flavors FROM people,favorite WHERE name ='judy' AND
name.favourite =favorite.key;

--
Geoff Berrow (put thecat out to email)
It's only Usenet, no one dies.
My opinions, not the committee's, mine.
Simple RFDs http://www.ckdog.co.uk/rfdmaker/
Jul 17 '05 #6
On Mon, 17 Nov 2003 17:37:41 +0000 (UTC), Disco Plumber
<sc**@moralmino rity.org> wrote:
aaron, doing a poor impression of Xerex, said:

I have a question about (i think) joining.


This is really more of an SQL question than a PHP question.
If I have a table in a database that has this info:
key - name - favorite
the favorite icecream table is this:
key - flavor


Here's TFM: http://www.mysql.com/doc/en/JOIN.html

Here's your simple answer, since I'm not a complete asshole (and also I
personally find it easier to learn from example):

$q = mysql_query("SE LECT * FROM people
LEFT JOIN favorites
ON people.favorite = favorites.key
WHERE name = 'judy'");
if(!$q) die("query failed\n");
if(!mysql_num_r ows($q)) die("no entry for judy\n");
$rec = mysql_fetch_ass oc($q);
echo "judy's favorite is $rec[flavor]\n";


I think you mean INNER JOIN, not LEFT JOIN; LEFT JOIN is the same as LEFT
OUTER JOIN, and so would only be applicable here if the database's referential
integrity was broken - i.e. judy's people.favourit e field didn't match any of
the keys in the favourite icecream table, but you still wanted the people row.
Doing an outer join where an inner join is really wanted may have performance
implications as well.

--
Andy Hassall (an**@andyh.co. uk) icq(5747695) (http://www.andyh.co.uk)
Space: disk usage analysis tool (http://www.andyhsoftware.co.uk/space)
Jul 17 '05 #7
Andy Hassall (79.740% quality rating):

I think you mean INNER JOIN, not LEFT JOIN; LEFT JOIN is the same as LEFT
OUTER JOIN, and so would only be applicable here if the database's
referential integrity was broken - i.e. judy's people.favourit e field
didn't match any of the keys in the favourite icecream table, but you
still wanted the people row.
I did mean the LEFT JOIN, but I usually opt for more information rather
than less and do extra error-checking in my PHP code.
Doing an outer join where an inner join is really wanted may have performance
implications as well.


Well, I'm no DBA, but I wouldn't expect a LEFT JOIN with an ON clause to
be that much worse than an INNER JOIN with a WHERE clause equating to
roughly the same thing. Is there an order of magnitude difference?

/joe
--
In El Myr, some bastard from IS kisses David Maynor, and then powers up a
preprocessor from Ryan Chaves. A huggable sorority house from Steve
Simonsen will go to Stevie Strickland.
Jul 17 '05 #8
On Mon, 17 Nov 2003 19:30:11 +0000 (UTC), Disco Plumber
<sc**@moralmino rity.org> wrote:
Andy Hassall (79.740% quality rating):

I think you mean INNER JOIN, not LEFT JOIN; LEFT JOIN is the same as LEFT
OUTER JOIN, and so would only be applicable here if the database's
referential integrity was broken - i.e. judy's people.favourit e field
didn't match any of the keys in the favourite icecream table, but you
still wanted the people row.


I did mean the LEFT JOIN, but I usually opt for more information rather
than less and do extra error-checking in my PHP code.


OK, but I'd argue that if you needed an outer join in this specific case, then
the database is broken; referential integrity checks really belong in the
database (although the real world sometimes gets in the way of that). Even
MySQL 3.x has foreign key constraints now.
Doing an outer join where an inner join is really wanted may have performance
implications as well.


Well, I'm no DBA, but I wouldn't expect a LEFT JOIN with an ON clause to
be that much worse than an INNER JOIN with a WHERE clause equating to
roughly the same thing. Is there an order of magnitude difference?


Well, It Depends. But any time you fetch more data than you need, there's a
difference. And once you get past trivial queries, using outer joins where
they're not needed can certainly change for the worse and constrain the access
paths your database can use.

--
Andy Hassall (an**@andyh.co. uk) icq(5747695) (http://www.andyh.co.uk)
Space: disk usage analysis tool (http://www.andyhsoftware.co.uk/space)
Jul 17 '05 #9
Disco Plumber (74.510% quality rating):

Well, I'm no DBA, but I wouldn't expect a LEFT JOIN with an ON clause to
be that much worse than an INNER JOIN with a WHERE clause equating to
roughly the same thing. Is there an order of magnitude difference?


The only information I found regarding this in MySQL's docs was:

http://www.mysql.com/doc/en/LEFT_JOIN_optimisation.html

which implies that LEFT JOINS have extra optimization done.

Regardless, the database implementation should not be my concern as a
PHP programmer. If I am doing valid SQL queries with fairly sound logic
(i.e., putting the processing in the right places, not making
unnecessary amounts of queries), the underlying implementation of one
JOIN versus another should be irrelevant to me. Of course, if I am
querying for information I'm not going to use (e.g., if I was going to
ignore those rows of the result where fields came back NULL), that is a
waste of processing.

But anyway I decided to write a script to do benchmarks for myself...

And the results are almost random (load dependent). There's no clear
winner. Of course, MySQL may be doing caching. But then, MySQL would be
doing caching for the actual service as well.

For reference:

$ mysql --version
mysql Ver 11.16 Distrib 3.23.49, for pc-linux-gnu (i686)

Check out a handful of the test results:

500 left joins (on): 1.480120 sec
500 inner joins: 0.505901 sec
500 left joins (using): 0.549247 sec

500 left joins (on): 1.678084 sec
500 inner joins: 0.723299 sec
500 left joins (using): 0.877342 sec

500 left joins (on): 0.488853 sec
500 inner joins: 0.696226 sec
500 left joins (using): 0.481876 sec

1000 left joins (on): 0.975070 sec
1000 inner joins: 1.654450 sec
1000 left joins (using): 0.969804 sec

1000 left joins (on): 0.993082 sec
1000 inner joins: 1.018203 sec
1000 left joins (using): 1.094612 sec

10000 left joins (on): 10.364384 sec
10000 inner joins: 11.173975 sec
10000 left joins (using): 13.425231 sec

10000 left joins (on): 11.104748 sec
10000 inner joins: 13.026637 sec
10000 left joins (using): 9.970058 sec

10000 left joins (on): 10.662058 sec
10000 inner joins: 10.493683 sec
10000 left joins (using): 16.690147 sec

Here's the script I used:

#!/usr/bin/php4 -q
<?php

include("common .php"); // database connection

define('ITERATI ONS', 10000);

function diff($start, $end) {
list($stu, $sts) = explode(" ", $start);
$start = (float)$stu + (float)$sts;
list($etu, $ets) = explode(" ", $end);
$end = (float)$etu + (float)$ets;
return (float)($end - $start);
}

function bench($query, $desc) {
$start = microtime();
for($i=0;$i<ITE RATIONS;$i++)
mysql_query($qu ery);
$end = microtime();
$diff = diff($start, $end);
printf("%d %s: %f sec\n", ITERATIONS, $desc, $diff);
}

bench("SELECT * FROM users LEFT JOIN user_settings
ON users.uid = user_settings.u id
WHERE uname = 'phatjoe'",
"left joins (on)");

bench("SELECT * FROM users,user_sett ings
WHERE users.uid = user_settings.u id
AND uname = 'phatjoe'",
"inner joins");

bench("SELECT * FROM users LEFT JOIN user_settings
USING (uid)
WHERE uname = 'phatjoe'",
"left joins (using)");

?>

/joe
--
A dead relative's processor from the 118 will go to Myke.
Jul 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
3527
by: Lenz Grimmer | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, MySQL 4.0.14, a new version of the popular Open Source/Free Software Database, has been released. It is now available in source and binary form for a number of platforms from our download pages at http://www.mysql.com/downloads/ and mirror sites.
0
3948
by: Mike Chirico | last post by:
Interesting Things to Know about MySQL Mike Chirico (mchirico@users.sourceforge.net) Copyright (GPU Free Documentation License) 2004 Last Updated: Mon Jun 7 10:37:28 EDT 2004 The latest version of this document can be found at: http://prdownloads.sourceforge.net/souptonuts/README_mysql.txt?download
1
2559
by: Cern | last post by:
Is it somebody out there who has made a migration from an Oracle server to an MySQL server?? The scenario is as simply: I've got a Oracle 8 server with a database with content that I want to transfer to a MySQL database. No special data, constraints etc that MySQL not will handle. My solution is to reverse engineer the database from ERStudio and then produce a SQL script that will insert the data into the MySQL engine. But I can't do...
1
3379
by: jlee | last post by:
I'm pretty much a newbie on mysql, and I need some help. I am running mysql Ver 12.22 Distrib 4.0.24, for portbld-freebsd5.4 (i386) on a server hosting an active website. The site's developer uses his own php shopping cart to receive customer orders. The configuration was done via cPanel with no external modifications - which produced no protests when built, ran and connected with no
1
2830
by: Good Man | last post by:
Hi there I've noticed some very weird things happening with my current MySQL setup on my XP Laptop, a development machine. For a while, I have been trying to get the MySQL cache to work. Despite entering the required lines to "my.ini" (the new my.cnf) through notepad AND MySQL Administrator, the cache does not work. So, today I took a peek at the 'Health' tab in MySQL Administrator.
3
6092
by: Juan Antonio Villa | last post by:
Hello, I'm having a problem replicating a simple database using the binary log replication, here is the problem: When the master sends an update to the slave, an example update reads as follows: UPDATE MainInfo SET dAddress='38 Holland Blvd', dCity='miami', dState='FL', dZip='33000', dCountry='USA', dPhone='999987565', dNum='AC15857', dName='Michael A Scott' WHERE did=22'
1
15391
by: Ike | last post by:
Recently, I began using a different MySQL verver (i.e. different machine as well as different version#, going from 4.12a to 4.1.9 max). The following query used to work: select firstname, lastname, from associates where username like 'nancianne' but now fails with: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from associates
3
8515
by: Me Alone | last post by:
Hello: I am trying to edit some C code I found in "The definitive guide to using, programming, and administering MySQL" by Paul DuBois. This C client program connects and then segfaults when the function load_image is called. Would anyone be able to point me to what I might be doing wrong? Thanks in advance, C Newbie
221
367735
Atli
by: Atli | last post by:
You may be wondering why you would want to put your files “into” the database, rather than just onto the file-system. Well, most of the time, you wouldn’t. In situations where your PHP application needs to store entire files, the preferred method is to save the file onto the server’s file-system, and store the physical location of the file in your database. This is generally considered to be the easiest and fastest way to store files. ...
0
9621
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10267
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10046
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8939
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7463
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6717
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3611
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2852
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.