Nov 23, 2009
Pages: 1, 2, 3

MySQL, Multiple Tables

free web hosting

Read Latest Entries..: (Post #27) by iGuest on Oct 14 2009, 07:15 AM.
Joins between many to many relationships MySQL, Multiple Tables Hi Guys, I'm struggling to understand the Join statements - I've seen many Examples of the Joins between one to many - many to one relationships - But none with many to many - where we have one main table - joint table - lookup table. I would most probably do it this way: SELECT * FROM shoes AS sh, colours AS col, shoes_colurs AS shc WHERE sh.Id = shc.Shoe AND col.Id = shc.Colour ORDER BY sh.Name ASC Now - it would ob...
read more.
Read the FIRST post of this Topic. - Express your Opinion! Contribute Knowledge :-).

Open Discussion & Free Web Hosting > Computers & Tech > Databases

MySQL, Multiple Tables

nightfox
Ok, I'm coding a project which is a leap than what I'd normally do. Before, I've always learned ONE table... put EVERYTHING in one database table.

I'm making a profile system so there needs to be at least two tables: 1 for users, 1 for content. My problem is, how do I link the two together? I could probably figure this out faster if someone explained and posted sample SQL code that shows how the two are linked together.

Thanks!!

[N]F

Comment/Reply (w/o sign-up)

Vyoma
There are multiple ways of linking two tables, and it would depend on what exactly do you want to link these two tables to choose between them.

For most of the cases a JOIN of the tables works and in some complex cases one would require to go for INNER QUERIES. Note that if you are planning on using MySQL as your database, as far as my knowledge goes, the present version does not support INNER QUERIES. (People, correct me if I am wrong here).

Now what are JOINs? Well, ther are many different types of JOINS: Self Joins, Natural Joins, Inner and Outer Joins. Explaining them would take a lot of verbiage tongue.gif and instead I will just show a sample of JOIN query between two tables. (You may extend it to multiple tables.

Now, I am assuming here that you have two table 'users' and 'content'.

I am putting here some of the columns that I think may be present in these tables:

users
-userid (PK)
-name
-password

content
-contentid (PK)
-userid (FK)
-contenttext

The above columns are minimal, and you may need to add more. But for the sake of explaining JOINs, these should be sufficient.

Now, assume that data if filled in both the tables. The ones in 'users' table is straight forward. The data is put in 'content' table with 'userid' being a foreign key. This means, the content's author is that particular user.
userid and contentid are Primary Keys (hence PK), and userid in 'content' table is a Foreign Key (FK).

Now, we will see the SQL of how to retrive a particular content specified by contentid, along with the author name.
CODE

SELECT c.contentid, c.contenttext, u.name
FROM content c, users u
WHERE c.contentid = $cntntid
AND c.userid = u.userid


Note that c.contentid = $cntid part in the WHERE clause is like you would use in retrieving data from one table. ($cntid is just a PHP variable - you may replace it by any value, that is hard code it or pass it by any other means).

Now, what compromises of a join? Yes, the c.userid = u.userid joins these two tables. The result of the query is that it will fetch content id and content text is picked up from 'content' table and author name is picked up from 'users' table.


I have assumed a lot many things above, but if you want something specific, please do ask.

 

 

 


Comment/Reply (w/o sign-up)

vhortex
Vyoma is correct..

I know of atleast 30 ways to connect the data together and they work on different versions of mySQL.. some are version specific and some are not..

what the post above shows is the basic way of doing stuffs with connecting data.

--

if you cant understand how joins work.. i can teach you how to do the same thing without the join command but this will be a little longer query.

the sample table structure will remain the same since it is a good basic sample for your current needs.

Comment/Reply (w/o sign-up)

yordan
It seems that nightfox starts learning what is a relationnal database, and why using relations is more interesting than using single tables.

Comment/Reply (w/o sign-up)

Quatrux
QUOTE(yordan @ Jul 26 2006, 01:41 AM) *

It seems that nightfox starts learning what is a relationnal database, and why using relations is more interesting than using single tables.


Yeah, agreed, that is the "fun" way to create something like this, but for me sometimes it gives a big headache how to do it "the best way".. I used to do databases with text files making them work by directories and file names and text inside, so you can imagine how my things got a lot more easier when I started getting into MySQL. wink.gif

Comment/Reply (w/o sign-up)

nightfox
QUOTE(Vyoma @ Jul 25 2006, 12:23 AM) *

There are multiple ways of linking two tables, and it would depend on what exactly do you want to link these two tables to choose between them.

For most of the cases a JOIN of the tables works and in some complex cases one would require to go for INNER QUERIES. Note that if you are planning on using MySQL as your database, as far as my knowledge goes, the present version does not support INNER QUERIES. (People, correct me if I am wrong here).

Wow, that's a lot! tongue.gif I'll have to find some time to read it all and absorb it! lol

[N]F

Comment/Reply (w/o sign-up)

Chesso
I usually just get the necessary information first and check it when needed later on.....

Or with user things their username/password is registered using $_SESSION and sometimes other bits of data that I can verify their signed in and who they are and whether they are banned and such.

Comment/Reply (w/o sign-up)

vhortex
QUOTE(yordan @ Jul 26 2006, 06:41 AM) *

It seems that nightfox starts learning what is a relationnal database, and why using relations is more interesting than using single tables.


on my first tries.. i completely rewritten and restructured my whole database..
i started on 1 table then jump to 5 tables..

since there is no connection, the database is easy..
when i consider space saving and verification system..

i need to link them together.. how painfull the headache was..

--

when i bump into transactional database.. the pain and suffering grows much more..

i do now most of the initial designs on paper and always takes 3 rechecks before
i create the actual database..

--
thanks to nested quries, i have manage to avoid joins.. =)

Comment/Reply (w/o sign-up)

nightfox
OK... I'm stuck and getting frustrated... I have two tables:
-users
-content

The users table contains the following:
-id
-user
-pass
-access_name

The content table contains the following:
-id
-content

Here's my test file code:
CODE

<?php
$username = "root";
$password = "";
$hostname = "localhost";    
$database = "join-test";
$dbh = mysql_connect($hostname, $username, $password)
    or die("Unable to connect to MySQL");
mysql_select_db($database)
    or die("Unable to connect to database. Check connection settings.");
// #############################################
$active_user = $_GET['id'];
// #############################################
$sql = "SELECT * FROM `users, content` WHERE `access_name`='".$active_user."' AND `users.id`=`content.id`";
$row = mysql_fetch_array(mysql_query($sql));
if($row['id']!="") {
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>

<body>
<?php
echo("User's profile:<br>".$row["content"]."");?>
</body>
</html>
<?php
}else{
die("<h1>Invalid ID or General Error</h1>");
}
?>
<?php
mysql_close($dbh);
?>

which gives me the following error whenever I try to access it even WITH a VALID access name:
QUOTE

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\Program Files\xampp\htdocs\mysql-joins\test.php on line 14
Invalid ID or General Error


I think I joined the tables wrong with:
$sql = "SELECT * FROM `users, content` WHERE `access_name`='".$active_user."' AND `users.id`=`content.id`";
but I'm not sure how it should be. I've been googling for about an hour and I'm really confused on how this should be!

[N]F

Comment/Reply (w/o sign-up)

Chesso
Ok well from what I know, when asking for something from two differen things, I *don't think* (not sure) that you should have `` around the two, maybe around both or not at all.

Also using WHERE `something` = `something`, I don't think that it is right, try surrounding = `something` in single ''s instead of ``. Same for normal variables like $my_var you can just do, `someval` = '$someval'.

Hope that helps, I'm really puzzled as to why you surrounded two things in one set of `'s but it could be something I haven't needed to use yet.

Here's what I would try your sql as:

$sql = "SELECT * FROM `users`, `content` WHERE `access_name`='$active_user' AND `users.id`= 'content.id'";

How does users.id and content.id work anyway. You are most likely getting the error on trying to fetch the array because the syntax is wrong or something you try to grab does not exist (meaning it could still mean wrong syntax).

Comment/Reply (w/o sign-up)

Latest Entries

iGuest
Joins between many to many relationships
MySQL, Multiple Tables

Hi Guys,

I'm struggling to understand the Join statements - I've seen many Examples of the Joins between one to many - many to one relationships - But none with many to many - where we have one main table - joint table - lookup table.

I would most probably do it this way:

SELECT * FROM shoes AS sh, colours AS col, shoes_colurs AS shc WHERE sh.Id = shc.Shoe AND col.Id = shc.Colour ORDER BY sh.Name ASC

Now - it would obviously work fine, but the question is - is there a better approach - using perhaps JOIN statement?

This is very simple statement - but I have one which is referring To a larger number of the joint tables as one entity can have more many To many relationships - and this kind of approach can generate quite Long statement - this is why I'm wondering if there's a better approach To this one.

Your help would be appreciated.

-reply by Mark

Comment/Reply (w/o sign-up)

iGuest
get data from two tables plz plz help meout
MySQL, Multiple Tables

I need to write a query which get array of data from one table and then search in second table at basis of result..Please help me..I can forward my code its only return me one record and search that one rec in second table ..I wanna get  more then one rec Please Please Please help me out..

$show_months5="select * from job_application where email='$email'";
Echo "select * from job_application where email='$email'";
                         $result5=mysql_query($show_months5);
                        $get_array5=mysql_fetch_array($result5);
                                        $month5=$get_array5['job_id'];
                                      $show_month_inf="select * from job where job_id='$month5'";
                          echo "select * from job where job_id='$month5'";
                                     $result1=mysql_query($show_month_inf);

-question by moon


Comment/Reply (w/o sign-up)

iGuest
Multiple tables in MySQL
MySQL, Multiple Tables

Replying to nightfoxIn the database I worked on in the 1960s things were so much easier - We just created a field name in the global dictionary that could directly accessa field from another table.
-reply by Leon Wooldridge

Comment/Reply (w/o sign-up)

darkken
i would recommend reading up on the t1 t2 commands for mysql. it is in the mysql manuel files.
CODE
$sql = "SELECT t1.name, t2.location FROM users t1, profiles t2"



Comment/Reply (w/o sign-up)

iGuest
Retrieving Data from Multiple Table
MySQL, Multiple Tables

Table1
Id
Full_name

Table2
Id
Contact_address

Table3
Id
Products

Query option as below
I want to search
? full_name <>
? contact_address <>
? products <>

But record in the format of

Id | full_name | contact_address | products


Please help me the good performance tunning codes. (database in mysql and script language is PHP)

Thanks!

-question by Krishna Aryal

Comment/Reply (w/o sign-up)


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

This textarea will convert to Rich-Text automatically (IE, Firefox, Chrome)

Pages: 1, 2, 3
Similar Topics

Keywords : mysql, multiple, tables

  1. Login System
    I want to make a login system using Mysql. I am amateur in these thing (12)
  2. Mysql Overhead
    (3)
    Sometimes in a table especially if i do alot of things in it i start seeing overhead then a size
    near it? what is overhead? and is it essential to optimize the table to fix it? I know its just a
    press of a button but i'd like to know what happens when i optimize a table. Also when you make
    a new table you can limit the size of VARCHAR to a number, that number would be the number
    characters allowed in that column per entry. I'd like to know how the limit works for texts, is
    it in KB? or number of characters? Cuz i made a messaging system. And i remember reading s....
  3. Mysql Multiple Tables
    (3)
    It is good practice to use multiple tables to sort out big amounts of data. But once you do that it
    becomes increasingly hard to cross reference the tables. Mysql has a little beautiful command
    structure that they have added. You can select multiple tables within one sql query. Example of a
    basic sql query CODE $sql = "SELECT * FROM table WHERE row=1"; If you noticed that I selected
    all of the rows in the table. Normally you will try to not select the entire table from the database
    unless you absolutely want all of the table. I would recommend against it; just gra....
  4. Any Website Provide Free Host Mysql Host?
    (4)
    any website provide free host mysql host? i need it because i am using 000webhost.com now but it
    only provide 2 mysql database... can i know where or how can i get more databases regards....
  5. Mysql On Computer
    XD (9)
    I posted PHP on computer? , but for some reason it doesn't show :/. Anyways I am wondering if
    there is MYSQL on my computer, meaning can i make a data base on my computer? that way i make what i
    want and upload it when i get hosted =)....
  6. Mysql Database Entry By Excel Sheets
    (2)
    Hello .. I would like to ask if i can use use Microsoft excel files in order to make entries to
    mysql database. Thanks....
  7. Mysql Database Management
    (1)
    Hi i am new, I have a problem in understanding the query decomposition in D-DB. Can anyone help me
    to understand the first question of the exercise 25.21 of Elmasri-Navath 4th edition? Consider the
    following relations: BOOKS (Book#, Primary_author, Topic, Total_stock, $price) BOOKSTORE (Store#,
    City, State, Zip, Inventory_value) STOCK (Store#, Book#, Qty) Consider a distributed database for a
    bookstore chain called National Books with 3 sites called EAST, MIDDLE, and WEST. Consider that
    BOOKS are fragmented by $price amounts into: B1:BOOK1:up to $20. B2:BOOK2:from ....
  8. Mysql And User File_priv
    (0)
    HI, I've hit the grain while trying to import file to mysql database - I need to enable file
    permissions of the database user but this seems not possible with most of the hosting providers.
    The problem is to set file_priv of the database user to "Y" . This is done in the "user" table of
    the maintanance database named "mysql". cPanel doesn't allow this. Via the cPanel you can only
    allow privileges on table querries but you cannot grant host file privileges to the database user -
    which makes querries like: "LOAD DATA INFILE 'filename' INTO TABLE tablen....
  9. I Have An Error With My Mysql Connection
    mysql connection error (7)
    ok so here's my web page... http://lacrossems.t35.org/ it only lags cause its trying to
    connect to the my sql server...i followed this guide
    http://forum.ragezone.com/showthread.php?t=387249 and when i edit my config.php to my host and
    login info i always get the error cannot connect to the database here is my config.php if you can
    help me CODE $host = 'CENSORED';                // my host $host =
    'righto';       // my database username $host = 'CENSORED';   // my database
    password $host = 'odinms';       // my datab....
  10. Mysql Backup With Another Address?
    (4)
    I just got my site hacked!! (don't worry because it is not on astahost) Actually it is a
    wordpress blog. So I backed up my MySQL Databases with cpanel. Now when I get my hosting approved
    here at astahost, can I restore those backups? Is the change of the site address going to interfere
    with this? Is there anyway I can edit those databases to work with my new address? Please help me
    out here!....
  11. Sun Bought Mysql
    (6)
    SUN bought the swedish company MYSQL for much money, around 2million each worker got in the company,
    they did it to come in to the database market, is it a good reson to buy it?....
  12. Mysql - So Hard
    Come in here if you think MySQL is soo hard! (14)
    Doesn't anybody think MySQL is so hard to code? I mean think about it, you need loads of
    databases just for one little script and you have to type things in like ;Host-Username:
    (blahblah) ;Host-Password: (blahblah) ;Host-DatabaseName: (blahblah) Ok, that MySQL code was
    random, and it is alot harder than that. If you have expierenced it being hard, you are free to
    post right in here, mate.....
  13. Login System Using A Mysql Db
    How do i do this? (5)
    Hi guys, ive got a registration system that looks something like the one below: Firstname:
    Lastname: Then i have inset.php, which looks like the following: $con =
    mysql_connect("localhost","autobot","abc123"); if (!$con) { die('Could not connect: ' .
    mysql_error()); }mysql_select_db("my_db", $con);$sql="INSERT INTO person (username, password) VALUES
    ('$_POST ','$_POST ')";if (!mysql_query($sql,$con)) { die('Error: ' .
    mysql_error()); } echo "1 record added";mysql_close($con) ?> Now my question is, how do i creat....
  14. Mysql And Php
    When trying to install Joomla (16)
    I don't know if this is the correct forum, but here is my question: I'm trying to test
    Joomla and some forums in my computer, I have already installed MySQL with the GUI tools, Apache,
    and PHP with the MySQL and MySQLi extensions, but when I'm trying to install Joomla I get this
    error: Required Settings Check: ------------------------------------- PHP version >= 4.1.0
    Yes - zlib compression support Available - XML support Available - MySQL support
    Unavailable configuration.php Writeable Session save path Unwriteable Not ....
  15. Navcat For MySQL
    is Navcat any good? (9)
    Hello all, i ve recently come across NavCat (GUI tool) for MySQL. I have not bought a copy yet, just
    played around with the demo. Has any one used it beore, if so please let me know if its worth
    buying. I already have PhpMyadmin, Just wanna know if NavCat is better than PhpMyAdmin in usibility
    and functionality. Regards....
  16. Is It A Good Practice To Store Image Or Other Binary Files Directly In A Mysql Database
    (6)
    Hello to all of you beautifull people out there, I am new to MySQL, i just wanted to know if its a
    good practice to directly store images and other binary files in a MySQL database. Any one with
    help? Thanks....
  17. Linking Two Tables
    (12)
    I have two tables in a database. userid and usercredits In userid I have all the fields that
    identify the user (name, address etc.) In my usercredits table I have the following fields: IDNUM
    ProgramName Camp# CompletionDate Amount DatePmtSent PmtMethod Comments creditID What I would like
    to understand about my table structure, is how do I associate my credits tothe correct user. If I
    have done this correctly, there is also a field in the first table that is called IDNUM where each
    user has a unique number to identify who they are. When someone is logged into the ....
  18. Updating A Database's Tables
    (11)
    Is there an "easy" way to update a database's tables? Like for instance, I have my own
    custom-coded member login system. Whenever I add a new feature that needs a database, I manually
    have to download, update and upload the database. Is there an easy way I can do this? THANKS!!! F....
  19. MySQL Output Database Question
    (19)
    I am new to MySql and have just created a database after using a script. My problem is not the
    script, but what it says about putting it into the output file. I cant figure out the right terms
    to put it in, I keep getting errors. I try using; SELECT*FROM 'database name' WHERE
    'location' but it isnt working. I'm lost with this stuff, I really am. Can someone
    please help me out?....
  20. MS-database To MySQL
    I'd like to batch them (6)
    Hi, maybe one of you already came across this, so I ask. I'll continue searching on. I've
    got two vocable trainers, one is Windows-native, the other one is on the web. While I can't
    control the output of the Windows-thing (so I can't export them to a *csv or something), I can
    write an import script. But since I'm not that great with Regular Expressions and don't know
    anything about *.mdb (that is MS SQL, isn't it?) files, I would need some finished thing to make
    out the field information and put it in arrays or something more readable. It wou....
  21. What Are The Alternatives To MySQL
    (7)
    Hi. i'm interested in alternatives to MySql combined with php. what database else can i use to
    create a webbased managment system with a lot of entries. maybe more than mysql can handle fast
    enough. it should be more powerful than mysql and should have nearly the same features. i hope
    there is a webbased administration program like phpmysqladmin thanks for your help ! greetings c.....
  22. How To Connect MySQL With Flash?
    Help me connect my flash Work with MySql (8)
    I know Flash and mysql but could not figure out if I could ever connect these? I want to have a
    dynamic content in my flash object that could be retrieved from the database directly without myself
    needing to update it again and again. How can I achieve this ? Do I have to install any additional
    controls or connectors to do that ? If yes any one tell me....
  23. Mirror My MySQL Database To Another Mysql Server
    (7)
    Hi..I want to ask if its possible to automatically mirror my mysql databases into another mysql
    server?or create a small php script to do this? The reason is because, we all know that database is
    very improtant if we have dynamic website. I have my forum hosted and i want to automatically
    mirror this or backup into another mysql server(free). Like in freesql.org. So that im not afraid
    that i forgot to backup my database..also i have one central backup database. Thanks for the
    help..Im looking forward for this posibility.....
  24. Recover Tables From A MySQL .frm File
    (9)
    I have a couple of .frm files with no corresponding data or index files. Is it possible to recover
    the table structure (field names, types, sizes, rows,col, etc) from these files? The table type is
    innodb....
  25. MySQL Database Problems
    (8)
    My friends have a little forum running here . The problem is that quite often we get the following
    message when we try to open the page: QUOTE Warning: mysql_connect(): Can't connect to
    local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in
    /home/vhosts/rohit.bizhat.com/forums/db/mysql4.php on line 48 Warning: mysql_error(): supplied
    argument is not a valid MySQL-Link resource in /home/vhosts/rohit.bizhat.com/forums/db/mysql4.php on
    line 330 Warning: mysql_errno(): supplied argument is not a valid MySQL-Link resource in
    /home/vhosts/roh....
  26. Error In Installing MySQL Server
    MySQL server cannot be started (9)
    I try to upgrade my MySQL server from 4.018 to 4.1.10a. Firstly, I downloaded mysql-4.1.10a (not the
    essential one) for win XP Then I install the new version after the old version was uninstalled.
    After the installation process, Instance Configurator comes up to help for the configuration. But an
    error occured when it try to start the MySQL service. Error messageis "cannot create windows
    service for MySQL. Error:0" So my MySQL server cannot be started. It is running win XP on my
    computer. Does anybody can tell me what is wrong?. Thanks (sorry for my bad english)....
  27. How Can I Import Csv Files To My MySQL Database?
    I was able to export but where's import? (3)
    I am having hard times finding that import csv in the mysql phpmyadmin. I once worked on some csv
    files and someone imported it on the mysql server. I was not able to ask him. Does someone know how
    can I import csv files in mysql server?....
  28. MySQL Datetime --> VB.NET Datetime Conversion Prob
    Any solutions ?? (4)
    Hi, Can anyone provide me with a quick example of fetching a MySQL Datetime Field and converting it
    into native VB.NET DateTime format ?? Say for example my db contains a couple of fields: Field1,
    Field2, DateField... one of which is the default MySQL DateTime. Say I'm using the following
    code to connect... CODE ConnectionString = "....." QueryString = "SELECT * FROM SomeTable" Dim
    myConnection As New MySql.Data.MySqlClient.MySqlConnection(ConnectionString) Dim myCommand As New
    MySql.Data.MySqlClient.MySqlCommand(QueryString, myConnection) Dim myReader As MySq....
  29. MySQL Realtime Replication
    how to replicate mysql in realtime (4)
    i dont know if this might be useful to ppl here, but this is a very good knowledge for serious
    siteadmins. while i was digging for mysql backup techniques, i've found that mysql is able to
    do realtime replication. the idea is that there are master server and slave server. both are having
    the same version of mysql installed. the data flows; Master >copy> Slave ( in realtime!)
    you'll never have to manually copy the database file of wasting your time to manually use the
    mysqldump command. here are the links; http://dev.mysql.com/doc/mysql/en/Replication_HOWTO.h....
  30. MySQL - Trouble With Bulk Insert Statements
    (3)
    I'm trying to insert about 500 rows into mysql, but I keep getting errors. If I copy and paste
    too many (about 50) insert statements at a time I get errors sometimes. I sometimes even get errors
    but then the row is skipped so I don't know there was an error (I'm using linux and SSH).
    What's the best way to get my insert statements to put the data in MySQL? Is there anyway that I
    can have it tell me if there where any errors all the statements are executed? Thanks for your
    help.....

    1. Looking for mysql, multiple, tables

See Also,

*SIMILAR VIDEOS*
Searching Video's for mysql, multiple, tables
advertisement



MySQL, Multiple Tables

Affordable Web Hosting, Low cost Web Hosting - ComputingHost.com