So a user selects from a drop down list a value. I take this value, put it into a variable, then select from the database the ID value of that table A holding the selected value also.
So now I'm trying to use that ID value to get to a many-to-many relationship table that has the selected value from table A to a different table B. The many-to-many relationship table has both IDs. How can I compare this using PHP?
So it would be like:
$A = $_POST['a'];
$sql = "SELECT a, aID from TABLEA WHERE a = $A";
What do I do then to compare the aID with the many-to-many relationships table, then get the other ID in that table and then take that ID to get values from table B?
You can do this with a join in your SQL:
SELECT table_b.* FROM ab_association
LEFT JOIN table_b ON table_b.id = ab_association.b_id
WHERE ab_association.a_id = $specified_id;
That assumes that your many-to-many join table is called ab_association and has two columns, one called a_id that corresponds to table_a.id, and b_id that corresponds to table_b.id.
Update: I removed the table name aliases since they seem to be confusing you.
Another Update: In PHP, here's how you would do that (sans business logic):
<?
// connect to db here
$a_id = mysql_real_escape_string($_POST['a_id']);
$result = mysql_query("SELECT table_b.* FROM ab_association LEFT JOIN table_b ON table_b.id = ab_association.b_id WHERE ab_association.a_id = $a_id;");
// in your view/template
while(false !== (mysql_fetch_object($result))) {
// build your output for each row
}
?>
SELECT *
FROM table_a
LEFT JOIN ab_association ON table_a.aID = ab_association.aID
LEFT JOIN table_b ON table_b.bID = ab_association.bID
WHERE table_a.a = $A
Notes:
I used some underscores in tablenames, so table_a instead of TABLEA (just like Coreyward did) to distinguish between sql and names
You should specify the columns you need instead of 'SELECT *' if many columns aren't needed
You can use JOIN instead of LEFT JOIN if you want get an empty recordset when no match in the many-to-many is found. (Using a LEFT JOIN has the advantage you still have access to the columns in table_A)
it is never wise to use $_POST-vars directly in your queries, this is a serious security risk (SQL injection.)
Related
My sql:
SELECT * FROM ex_pair
LEFT JOIN ex_currency as client
ON client_curr = currency_id
LEFT JOIN ex_currency as company
ON co_curr = currency_id
I need to get data for two currency_id but I have an error
ambiguous column name: 'currency_id'
Is there any way to do it right or i need to use two queries?
You need to include your alias in your join, like this:
SELECT *
FROM ex_pair
LEFT JOIN ex_currency AS client
ON client_curr = client.currency_id
LEFT JOIN ex_currency as company
ON co_curr = company.currency_id
You may also want to do something other than select * as you will have two tables with the same columns - something like
SELECT pair.*, company.currency_id AS company_currency_id, client.currency_id as client_currency_id, [...]
FROM ex_pair AS pair
[...]
This way when you explicitly declare the columns you intend to use from ex_currency with an alias, you can know on the other end more easily which are client and which are company. You will need to do this for each column in the currency table that you want in your result, though that can be done if you have your table structure in your code easily enough by looping over the list of columns and appending the alias.
$array = [
1=> "currency_id",
2=> "currency_name"
];
$columns = ""
foreach($array as $column){
$columns.= "company.".$column." AS company_".$column;
$columns.= ",client.".$column." AS client_".$column.",";
}
$columns = rtrim($columns,',');
Gives you
company.currency_id AS company_currency_id,client.currency_id AS client_currency_id,company.currency_name AS company_currency_name,client.currency_name AS client_currency_name
Add that after your SELECT pair.* and you get your columns from the currency table, aliased so you know which is which.
you can use the alias that you give to the tables:
SELECT client.currency_id as client_currency, company.currency_id as company_currency
FROM ex_pair
LEFT JOIN ex_currency as client ON client_curr = client.currency_id
LEFT JOIN ex_currency as company ON co_curr = company.currency_id
I keep falling back into questions with MySQL joining.
And I would like to request a very simple example I could use to continue my journey of understanding learning the MySQL syntax.
Let's say I got the following table's
test_testtable
testtable_id
testtable_name
testtable_user
testtable_option
testtable_textfield
test_testlink
testlink_id
testlink_link
testlink_address
test_address
address_id
address_name
address_phone
address_email
address_street
address_city
address_zip
I would like to make a selection like :
SELECT * (lets say I would define the fields) FROM `test_testable`
JOIN `test_testtable`.`testtable_id` = `test_testlink`.`testlink_link`
AND
JOIN `test_testlink`.`testlink_addres` = `test_address`.`address_id`
WHERE `user_id` = 5
Hence the linking structure is like:
test_testtable.testtable_id = leading
table test_testlink is a table to link the table test_testtable and test_address
And linking table test_testlink uses the field testlink_link to link to the table test_testtable, and uses the field testlink_address to link to the table test_address
This does not work. FOR ME.. Since I continuously seem to fail of catching the correct syntax logic.
So I hope that someone could give me a small example of how to correctly implement such a simple yet critical query!
TIAD!!
A general approach :
SELECT table1.* FROM table1
JOIN table2 ON table2.id_table1 = table1.id
JOIN table3 ON table3.id_table2 = table2.id
WHERE table1.id = 10
For your purpose :
SELECT * (lets say I would define the fields) FROM `test_testable`
JOIN `test_testlink` ON `test_testtable`.`testtable_id` = `test_testlink`.`testlink_link`
JOIN `test_address` ON `test_testlink`.`testlink_addres` = `test_address`.`address_id`
WHERE `user_id` = 5
Please read the reference
You are using wrong syntax. You should mention which tables to join first then based on which fields.
SELECT * (lets say I would define the fields) FROM `test_testable`
INNER JOIN test_testlink
ON `test_testtable`.`testtable_id` = `test_testlink`.`testlink_link`
INNER JOIN `test_address`
ON `test_testlink`.`testlink_addres` = `test_address`.`address_id`
AND `test_testtable`.`user_id` = 5
select * from testlink JOIN testtable ON testlink.tableid = testtable.ID
JOIN testaddress ON testlink.addressid = testaddress.ID
WHERE testtable.ID = 5
I have a mySQL db named relOwner that has two columns:
OwnerID, RelationshipOwner
I am writing a query with joins that references the db:
$query = "SELECT b.Contact, b.ContactB, relOwner.OwnerID, relOwner.RelationshipOwner
FROM b
Left JOIN relOwner
ON b.Contact = relOwner.OwnerID
Left JOIN relOwner
ON b.ContactB = relOwner.OwnerID
";
How do I reference the values of RelationshipOwner individually in my php?
$RelationshipOwner = $row['RelationshipOwner'];
$RelationshipOwnerB = $row['RelationshipOwner']; <--- Get value from second JOIN
Thanks in advance.
It seems that you have two foreign key columns on table b to table relOwner (viz Contact and ContactB).
As per Sverri's comment, you will need to use a different alias for the tables (I've used ro1 and ro2) , and project different names from the different table columns (e.g. prefix the second table columns with ro2):
SELECT b.Contact, b.ContactB, ro1.OwnerID, ro1.RelationshipOwner,
ro2.OwnerID as ro2OwnerId, ro2.RelationshipOwner as ro2RelationshipOwner
FROM b -- Is this table Contact? If so then "Contact b"
Left JOIN relOwner ro1
ON b.Contact = ro1.OwnerID
Left JOIN relOwner ro2
ON b.ContactB = ro2.OwnerID;
Which you can then reference:
$row['ro2RelationshipOwner'];
I have 2 tables.
Table A: trades: which contains the columns: tradeID, tradeName, tradeShow, and tradeGuy.
Table B: offers: which contains the columns: tradeID, offerName, offerGuy.
I'm trying to select all columns from table A (trades) WHERE the value of "tradeShow" = 'Yes', And the value of "tradeGuy" != the user's Username. That much is easy, but I also don't want to select any records which have an offer created by the user. In other words, in table B (offers), offerGuy != Username WHERE trade ID from Table B = tradeID from Table A.
But, how do I merge these 2 conditions? I've tried this:
$sql = "SELECT *
FROM trades t1
JOIN offers t2
ON (t1.tradeID = t2.tradeID)
WHERE t1.tradeShow='Yes' AND t1.tradeGuy!='$username' AND t2.offeringGuy!='$username'";
But the problem with that is it only selects the records from trades which have an offer, because of the forth line: ON (t1.tradeID = t2.tradeID), as in it only selects trades which have a record in (offers) that mentions their tradeID.
I've also tried an awkward attempt to link the 2 tables with a meaningless link by adding a "linker" column to each table with the default value of "XXX", and did this:
$sql = "SELECT *
FROM trades t1
JOIN offers t2
ON (t1.linkerA = t2.linkerB)
WHERE t1.tradeShow='Yes' AND t1.tradeGuy!='$username' AND (t2.offeringGuy!='$username' WHERE t1.tradeID=t2.tradeID)";
But the problem with that is using 2 Where clauses...
So, how do I merge the 2 conditions?
What you're looking for is called an OUTER JOIN (in this case a LEFT OUTER JOIN) which will give you null results for missing matches, something like;
SELECT *
FROM trades t1
LEFT OUTER JOIN offers t2
ON t1.tradeID = t2.tradeID AND t2.offeringGuy = '$username'
WHERE t1.tradeShow='Yes' AND t1.tradeGuy!='$username' AND t2.offeringGuy IS NULL
We add a condition to the LEFT JOIN that we're only interested in matches against t2.offeringGuy = '$username', which will return NULL values in t2's fields if there is no match.
Then we just check that t2.offeringGuy IS NULL to find the non matches.
I would do this with not exists rather than an explicit join:
SELECT *
FROM trades t
WHERE t.tradeShow = 'Yes' AND t.tradeGuy <> '$username' and
not exists (select 1
from offers o
where t.tradeID = o.tradeID and o.tradeGuy = '$username'
);
I have two tables, classified and fordon.
classified table:
classified_id (PK)
etc...
fordon table:
id (PK)
classified_id (FK)
I try to use this code:
SELECT * FROM classified, fordon WHERE classified.ad_id IN ('$solr_id_arr_imploded') AND classified.classified_id=fordon.classified_id
BTW, the array is a set of ad_id:s returned from solr, never mind that, that is not the problem here...
Then I use mysql_fetch_array in a while-loop to display all the results:
while($row = mysql_fetch_array($qry_result)){
but when I try to echo something which is inside the table fordon, then the index can't be found error appears. But whatever is inside the table classified works to echo!
Any ideas?
Thanks
UPDATE
while($row = mysql_fetch_array($qry_result)){
echo $row['type']; // This doesn't work, because the 'type' column is inside the 'fordon' table
echo $row['headline']; // This does work because it's inside 'classified' table.
Does this help?
SELECT *
FROM classified c
INNER JOIN fordon f ON c.classified_id=f.classified_id
WHERE classified.ad_id IN ('$solr_id_arr_imploded');
Also, its generally not a good idea to use: SELECT *. Its better to either select only the elements you want or use the * in context of the table you are getting all from, e.g.
SELECT classified.*
FROM classified c
INNER JOIN fordon f ON c.classified_id=f..classified_id
WHERE classified.ad_id IN ('$solr_id_arr_imploded');
When you do joins with a blanket * you get every field in all tables.